I need to convert from a standard Gregorian date to a Julian day number.
I've seen nothing documented in C# to do this directly, but I have found many posts (while Googling) suggesting the use of ToOADate.
The documentation on ToOADate does not suggest this as a valid conversion method for Julian dates.
Can anyone clarify if this function will perform conversion accurately, or perhaps a more appropriate method to convert DateTime to a Julian formatted string.
This provides me with the expected number when validated against Wikipedia's Julian Day page
public static long ConvertToJulian(DateTime Date)
{
int Month = Date.Month;
int Day = Date.Day;
int Year = Date.Year;
if (Month < 3)
{
Month = Month + 12;
Year = Year - 1;
}
long JulianDay = Day + (153 * Month - 457) / 5 + 365 * Year + (Year / 4) - (Year / 100) + (Year / 400) + 1721119;
return JulianDay;
}
However, this is without an understanding of the magic numbers being used.
Thanks
References:
OADate is similar to Julian Dates, but uses a different starting point (December 30, 1899 vs. January 1, 4713 BC), and a different 'new day' point. Julian Dates consider noon to be the beginning of a new day, OADates use the modern definition, midnight.
The Julian Date of midnight, December 30, 1899 is 2415018.5. This method should give you the proper values:
public static double ToJulianDate(this DateTime date)
{
return date.ToOADate() + 2415018.5;
}
As for the algorithm:
if (Month < 3) ...
: To make the magic numbers work our right, they're putting February at the 'end' of the year.(153 * Month - 457) / 5
: Wow, that's some serious magic numbers.
(int)(30.6 * Month - 91.4)
. 30.6 is the average number of days per month, excluding February (30.63 repeating, to be exact). 91.4 is almost the number of days in 3 average non-February months. (30.6 * 3 is 91.8).365 * Year
: Days per year(Year / 4) - (Year / 100) + (Year / 400)
: Plus one leap day every 4 years, minus one every 100, plus one every 400. + 1721119
: This is the Julian Date of March 2nd, 1 BC. Since we moved the 'start' of the calendar from January to March, we use this as our offset, rather than January 1st. Since there is no year zero, 1 BC gets the integer value 0. As for why March 2nd instead of March 1st, I'm guessing that's because that whole month calculation was still a little off at the end. If the original writer had used - 462
instead of - 457
(- 92.4
instead of - 91.4
in floating point math), then the offset would have been to March 1st.