Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

Q807 How can I subtract 12 months from a date in Julian form and decide whether to subtract 365 days or 366 days (when one of the months included in the 12 months is February and contains 29 days)?

You are here: irt.org | FAQ | JavaScript | Date | Q807 [ previous next ]

It depends what format your Julian date is in. If its the format: YYYYDDD then I would recommend converting this to a proper date: then checking to see if the date returned is the 29th of Feb, and if it is subtract 1 year and 1 day from the date instead of just 1 year.

Assuming that your Julian date format contains embedded zeros, e.g. 1999048 for today's date the 17th of February 1999., then you can extract the date and number of days quite simply with:

var myDate = '1999048';
var myYear = myDate.substring(0,3);
var myDays = myDate.substring(4,6);

This can then be used to create a date object for the relevant date:

var theDate = new Date(myYear,0,myDays);

Then you need to do is check that the date isn't the 29th of February:

if (theDate.getMonth() == 1 && theDate.getDate() == 29)
    theDate = new Date(myYear-1,0,myDays-1);
else
    theDate = new Date(myYear-1,0,myDays);

alert('Date last year = ' + theDate);

A test script to demonstrate that this works for Leap Days is shown below:

<SCRIPT LANGUAGE="JavaScript"><!--
var myDate = '2000060'; // 29th February 2000

var myYear = myDate.substring(0,4);
var myDays = myDate.substring(5,7);

alert(myYear + ' ' + myDays);

var theDate = new Date(myYear,0,myDays);

alert('Date now = ' + theDate);

if (theDate.getMonth() == 1 && theDate.getDate() == 29) {
    alert('February the 29th!');
    theDate = new Date(myYear-1,0,myDays-1);
}
else
    theDate = new Date(myYear-1,0,myDays);

alert('Date last year = ' + theDate);
//--></SCRIPT>

©2018 Martin Webb