Converting a Gregorian date to Julian Day Count in Objective C

前端 未结 2 888
日久生厌
日久生厌 2020-12-31 17:11

I need Objective C method for converting Gregorian date to Julian days same as this PHP method (GregorianToJD).

2条回答
  •  青春惊慌失措
    2020-12-31 17:50

    Precision: Incorporating time of day in Julian Date conversions

    These Julian date conversion methods yield results identical to the U.S. Naval Observatory's Online Julian Date Converter, which is more precise than NSDateFormatter's Julian Date conversion. Specifically, the functions below incorporate time-of-day (e.g. hour, minute and seconds), whereas NSDateFormatter rounds to noon GMT.

    Swift examples:

    func jdFromDate(date : NSDate) -> Double {
        let JD_JAN_1_1970_0000GMT = 2440587.5
        return JD_JAN_1_1970_0000GMT + date.timeIntervalSince1970 / 86400
    }
    
    func dateFromJd(jd : Double) -> NSDate {
        let JD_JAN_1_1970_0000GMT = 2440587.5
        return  NSDate(timeIntervalSince1970: (jd - JD_JAN_1_1970_0000GMT) * 86400)
    }
    

    Objective-C examples:

    double jdFromDate(NSDate *date) {
       double JD_JAN_1_1970_0000GMT = 2440587.5;
       return JD_JAN_1_1970_0000GMT + date.timeIntervalSince1970 / 86400;
    }
    
    NSDate dataFromJd(double jd) {
       double JD_JAN_1_1970_0000GMT = 2440587.5;
       return [[NSDate alloc] initWithTimeIntervalSince1970: (jd - JD_JAN_1_1970_0000GMT) * 86400)];        
    }
    

    Note: Research confirms that the accepted answer rounds the date to a 24-hour interval because it uses the g format-specifier of NSDateFormatter, which returns the Modified Julian Day, according to the UNICODE standard's Date Format Patterns that Apple's date formatting APIs adhere to (according to the Date Formatting Guide).

提交回复
热议问题