Convert Julian Date with Time (H/m/s) to Date Time in C#

雨燕双飞 提交于 2019-12-13 12:15:19

问题


How can I convert a Julian Date with Time - e.g. 2456961.090914 (CE 2014 October 30 14:10:54.6 UT) as you can test on this website: http://aa.usno.navy.mil/data/docs/JulianDate.php in C#?

I tried several algorithms I found on the net, but some don't contemplate the Julian as a double, only long or even int. Some other use DateTime.ToOADate that I do not have in the System.DateTime.

How can I convert the given Julian Date to a normal/regular DateTime?


回答1:


Thanks to Mr. Zator answer here I was able to solve my problem like so:

public DateTime JulianToDateTime(double julianDate) {
    double unixTime = (julianDate - 2440587.5) * 86400;

    DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
    dtDateTime = dtDateTime.AddSeconds(unixTime).ToLocalTime();

    return dtDateTime;
}

It is worth mentioning though, that this only works for CE Julian Date types, if the Julian Date is in BCE type it will not work, someother function is needed for that. I also made the opposite version of this method that looks like this:

public double DateTimeToJulian(DateTime dateTime) {
    DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
    TimeSpan diff = dateTime.ToUniversalTime() - origin;
    double unixTime = Math.Floor(diff.TotalSeconds);
    double julianDate = (unixTime / 86400) + 2440587.5;

    return julianDate;
}


来源:https://stackoverflow.com/questions/26655365/convert-julian-date-with-time-h-m-s-to-date-time-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!