Map iso8601 date time string to Julian Day using javascript

1.5k views Asked by At

Does anyone have a compact / elegant map from an ISO-8601 date time string of the following form:

2013-12-28T20:30:00-0700

To a Julian day. I'm hoping to find a solution that avoids an external library and has minimal regex and string manipulation.

1

There are 1 answers

8
Nate On

Here’s one way to do it.

You can convert an ISO string—with a time zone offset too—to a JavaScript Date object in modern JavaScript (ES5). This works in Node.js, Chrome and Firefox. It is not yet supported in Safari or IE. If you need it to work in all browsers, you have to parse the date yourself or use a library like Moment.js.

I tested this algorithm against the US Naval Observatory Julian Date Converter for a range of dates.

For dates prior to the Gregorian changeover (Oct. 15, 1582), this assumes the proleptic Gregorian calendar and will diverge from what the US Naval Observatory shows.

function julianDayNumber(d) {
  var epoch = 2440587.500000;                   // Jan. 1, 1970 00:00:00 UTC
  return d.getTime() / 86400000 + epoch;
}

Sample usage:

console.log(julianDayNumber(new Date('2013-12-28T20:30:00-0700')));
// prints: 2456655.6458333335