JavaScript Julian Day Conversions

Below are some useful JavaScript prototypes to handle Julian Day conversions.

Converting Date to Julian Day

1 Date.prototype.Date2Julian = function() {
2 return Math.floor((this / 86400000) -
3 (this.getTimezoneOffset()/1440) + 2440587.5);
4 };


 



Converting Julian Day to Date Object



1 Number.prototype.Julian2Date = function() {
2
3 var X = parseFloat(this)+0.5;
4 var Z = Math.floor(X); //Get day without time
5 var F = X - Z; //Get time
6 var Y = Math.floor((Z-1867216.25)/36524.25);
7 var A = Z+1+Y-Math.floor(Y/4);
8 var B = A+1524;
9 var C = Math.floor((B-122.1)/365.25);
10 var D = Math.floor(365.25*C);
11 var G = Math.floor((B-D)/30.6001);
12 //must get number less than or equal to 12)
13 var month = (G<13.5) ? (G-1) : (G-13);
14 //if Month is January or February, or the rest of year
15 var year = (month<2.5) ? (C-4715) : (C-4716);
16 month -= 1; //Handle JavaScript month format
17 var UT = B-D-Math.floor(30.6001*G)+F;
18 var day = Math.floor(UT);
19 //Determine time
20 UT -= Math.floor(UT);
21 UT *= 24;
22 var hour = Math.floor(UT);
23 UT -= Math.floor(UT);
24 UT *= 60;
25 var minute = Math.floor(UT);
26 UT -= Math.floor(UT);
27 UT *= 60;
28 var second = Math.round(UT);
29
30 return new Date(Date.UTC(year, month, day, hour, minute, second));
31 };


 


William Jefferys has an excellent write-up on Julian days here.


 

0 comments:

Post a Comment