Convert DateTime to Julian Date in C# (ToOADate Safe?)

前端 未结 6 1979
梦如初夏
梦如初夏 2020-11-27 18:34

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,

6条回答
  •  长情又很酷
    2020-11-27 19:00

    I use some calculations in microcontrollers but require years only between 2000 and 2255. Here is my code:

    typedef struct {
        unsigned int8   seconds;    // 0 to 59
        unsigned int8   minutes;    // 0 to 59
        unsigned int8   hours;      // 0 to 23  (24-hour time)
        unsigned int8   day;        // 1 to 31
        unsigned int8   weekday;    // 0 = Sunday, 1 = Monday, etc.
        unsigned int8   month;      // 1 to 12
        unsigned int8   year;       // (2)000 to (2)255
        unsigned int32  julian;     // Julian date
    } date_time_t;
    
        
    

    // Convert from DD-MM-YY HH:MM:SS to JulianTime

    void JulianTime(date_time_t * dt)
    {
        unsigned int8   m, y;
    
        y = dt->year;
        m = dt->month;
        if (m > 2) m -= 3;
        else {
            m +=  9;
            y --;
        }
        dt->julian  = ((1461 * y) / 4) + ((153 * m + 2) / 5) + dt->day;
        dt->weekday = ( dt->julian + 2 ) % 7;
        dt->julian  = (dt->julian * 24) + (dt->hours   ); 
        dt->julian  = (dt->julian * 60) + (dt->minutes );     
        dt->julian  = (dt->julian * 60) + (dt->seconds );     
    }
    

    // Reverse from JulianTime to DD-MM-YY HH:MM:SS

    void GregorianTime(date_time_t *dt) 
    {
        unsigned int32  j = dt->julian;
    
        dt->seconds = j % 60;
        j /= 60;
        dt->minutes = j % 60;
        j /= 60;
        dt->hours   = j % 24;
        j /= 24;
        dt->weekday = ( j + 2 ) % 7; // Get day of week
        dt->year = (4 * j) / 1461;
        j = j - ((1461 * dt->year) / 4);
        dt->month = (5 * j - 3) / 153;
        dt->day  = j - (((dt->month * 153) + 3) / 5);
        if ( dt->month < 10 )
        {
            dt->month += 3;
        }
        else
        {
            dt->month -= 9;
            dt->year ++;
        }
    }
    

    Hope this helps :D

提交回复
热议问题