本代码来自ReactOS-0.4.0\lib\rtl\time.c中的函数RtlTimeToTimeFields(IN PLARGE_INTEGER Time, OUT PTIME_FIELDS TimeFields);

源代码如下: 

#define TICKSPERMIN        600000000
#define TICKSPERSEC        10000000
#define TICKSPERMSEC       10000
#define SECSPERDAY         86400
#define SECSPERHOUR        3600
#define SECSPERMIN         60
#define MINSPERHOUR        60
#define HOURSPERDAY        24
#define EPOCHWEEKDAY       1
#define DAYSPERWEEK        7
#define EPOCHYEAR          1601
#define DAYSPERNORMALYEAR  365
#define DAYSPERLEAPYEAR    366
#define MONSPERYEAR        12

static const unsigned int YearLengths[2] = { DAYSPERNORMALYEAR, DAYSPERLEAPYEAR };
static const UCHAR MonthLengths[2][MONSPERYEAR] =
{
    { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
    { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
};

static __inline int IsLeapYear(int Year)
{
    return Year % 4 == 0 && (Year % 100 != 0 || Year % 400 == 0) ? 1 : 0;
}

static int DaysSinceEpoch(int Year)
{
    int Days;
    Year--; /* Don't include a leap day from the current year */
    Days = Year * DAYSPERNORMALYEAR + Year / 4 - Year / 100 + Year / 400;
    Days -= (EPOCHYEAR - 1) * DAYSPERNORMALYEAR + (EPOCHYEAR - 1) / 4 - (EPOCHYEAR - 1) / 100 + (EPOCHYEAR - 1) / 400;
    return Days;
}

VOID RtlTimeToTimeFields(IN PLARGE_INTEGER Time, OUT LPSYSTEMTIME TimeFields)
{
    const UCHAR *Months;
    ULONG SecondsInDay, CurYear;
    ULONG LeapYear, CurMonth;
    ULONG Days;
    ULONGLONG IntTime = Time->QuadPart;

    /* Extract millisecond from time and convert time into seconds */
    TimeFields->wMilliseconds = (WORD) ((IntTime % TICKSPERSEC) / TICKSPERMSEC);
    IntTime = IntTime / TICKSPERSEC;

    /* Split the time into days and seconds within the day */
    Days = (ULONG)(IntTime / SECSPERDAY);
    SecondsInDay = IntTime % SECSPERDAY;

    /* compute time of day */
    TimeFields->wHour = (WORD) (SecondsInDay / SECSPERHOUR);
    SecondsInDay = SecondsInDay % SECSPERHOUR;
    TimeFields->wMinute = (WORD) (SecondsInDay / SECSPERMIN);
    TimeFields->wSecond = (WORD) (SecondsInDay % SECSPERMIN);

    /* compute day of week */
    TimeFields->wDayOfWeek = (WORD) ((EPOCHWEEKDAY + Days) % DAYSPERWEEK);

    /* compute year */
    CurYear = EPOCHYEAR;
    CurYear += Days / DAYSPERLEAPYEAR;
    Days -= DaysSinceEpoch(CurYear);
    while (1)
    {
        LeapYear = IsLeapYear(CurYear);
        if (Days < YearLengths[LeapYear])
        {
            break;
        }
        CurYear++;
        Days = Days - YearLengths[LeapYear];
    }
    TimeFields->wYear = (WORD) CurYear;

    /* Compute month of year */
    LeapYear = IsLeapYear(CurYear);
    Months = MonthLengths[LeapYear];
    for (CurMonth = 0; Days >= Months[CurMonth]; CurMonth++)
        Days = Days - Months[CurMonth];
    TimeFields->wMonth = (WORD) (CurMonth + 1);
    TimeFields->wDay = (WORD) (Days + 1);
}

  

posted on 2017-06-15 17:10  我,猪八戒  阅读(287)  评论(0编辑  收藏  举报