Wednesday, February 01, 2006

Convert Julian Date to System.DateTime

Yesterday I had a requirement for converting Julian date to normal date and compare the date with a given date. I searched many times and I got Julian calendar and I didn't get any date conversion in .NET. But I got many examples in JavaScript how to convert Julian date to mm/dd/yyyy. I just converted JavaScript code to C#. Hope this helps to all you.


private DateTime ConvertJulianToDateTime(double julianDate)
{
DateTime date;
double dblA, dblB, dblC, dblD, dblE, dblF;
double dblZ, dblW, dblX;
int day, month, year;
try
{
dblZ = Math.Floor(julianDate + 0.5);
dblW = Math.Floor((dblZ - 1867216.25) / 36524.25);
dblX = Math.Floor(dblW / 4);
dblA = dblZ + 1 + dblW - dblX;
dblB = dblA + 1524;
dblC = Math.Floor((dblB - 122.1) / 365.25);
dblD = Math.Floor(365.25 * dblC);
dblE = Math.Floor((dblB - dblD) / 30.6001);
dblF = Math.Floor(30.6001 * dblE);
day = Convert.ToInt32(dblB - dblD - dblF);
if (dblE > 13)
{
month = Convert.ToInt32(dblE - 13);
}
else
{
month = Convert.ToInt32(dblE - 1);
}
if ((month == 1) (month == 2))
{
year = Convert.ToInt32(dblC - 4715);
}
else
{
year = Convert.ToInt32(dblC - 4716);
}
date = new DateTime(year, month, day);
return date;
}
catch (ArgumentOutOfRangeException ex)
{
MessageBox.Show("Julian date could not be converted:\n" + ex.Message, "Conversion Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
date = new DateTime(0);
}
catch (Exception ex)
{
MessageBox.Show("Error converting Julian date:\n" +
ex.Message, "Conversion Error", MessageBoxButtons.OK,
MessageBoxIcon.Error);
date = new DateTime(0);
}
return date;
}



To learn more about about Julian dates, visit http://quasar.as.utexas.edu/BillInfo/JulianDatesG.html

2 comments:

Chuck said...

Works like a charm. Nice piece of code. Just what I was looking for. Thanks alot...

John said...

Works, BUT I had to add logical OR in:
if ((month == 1) (month == 2))

Should be
if ((month == 1) || (month == 2))
...I guess?