VariantTimeToSystemTime 实现源码
时间: 2023-07-15 21:15:15 浏览: 32
VariantTimeToSystemTime 函数是将 Variant 时间值转换为系统时间值的函数。以下是该函数的实现源码:
```c++
BOOL VariantTimeToSystemTime(DATE dt, LPSYSTEMTIME lpSystemTime)
{
if (lpSystemTime == NULL)
return FALSE;
// 日期的整数部分是自 1899 年 12 月 30 日以来的天数
double dTemp = dt + HALF_SECOND / SECONDS_PER_DAY;
// 这个数字表示了 1900 年 1 月 1 日的日期
// 也就是说,它是 dTemp 中减去 2 的结果
int nDays = (int)dTemp;
// 将时间部分转换为 SYSTEMTIME 结构
double dblSecsInDay = dTemp - (double)nDays;
int nSeconds = (int)(dblSecsInDay * SECONDS_PER_DAY);
lpSystemTime->wHour = nSeconds / SECONDS_PER_HOUR;
nSeconds -= lpSystemTime->wHour * SECONDS_PER_HOUR;
lpSystemTime->wMinute = nSeconds / SECONDS_PER_MINUTE;
nSeconds -= lpSystemTime->wMinute * SECONDS_PER_MINUTE;
lpSystemTime->wSecond = nSeconds;
lpSystemTime->wMilliseconds = (WORD)((dblSecsInDay - (double)nSeconds) * 1000.0);
// 将日期部分转换为 SYSTEMTIME 结构
// 闰年必须是 4 的倍数,但世纪闰年必须是 400 的倍数
int nLeapYears = (nDays - DAYS_FROM_BASELINE_TO_1900) / 1461;
int nYear = 1900 + nLeapYears * 4;
int nDaysInLeapYear = (nDays - DAYS_FROM_BASELINE_TO_1900) % 1461;
for (;;)
{
int nDaysInYear = DaysInYear(nYear);
if (nDaysInLeapYear < nDaysInYear)
break;
nYear++;
nDaysInLeapYear -= nDaysInYear;
}
lpSystemTime->wYear = (WORD)nYear;
lpSystemTime->wMonth = 1;
int nMonth;
for (nMonth = 1; nMonth <= 12; nMonth++)
{
int nDaysInMonth = DaysInMonth(nMonth, IsLeapYear(nYear));
if (nDaysInLeapYear < nDaysInMonth)
break;
nDaysInLeapYear -= nDaysInMonth;
lpSystemTime->wMonth++;
}
lpSystemTime->wDay = (WORD)(nDaysInLeapYear + 1);
lpSystemTime->wDayOfWeek = (WORD)((nDays + 1) % 7);
return TRUE;
}
```
这段代码中包含了一些常量和辅助函数,它们的定义如下:
```c++
#define DAYS_FROM_BASELINE_TO_1900 693593
#define SECONDS_PER_DAY 86400
#define SECONDS_PER_HOUR 3600
#define SECONDS_PER_MINUTE 60
#define HALF_SECOND (1.0 / (2.0 * SECONDS_PER_DAY))
inline BOOL IsLeapYear(int nYear)
{
return ((nYear & 3) == 0) && ((nYear % 100) != 0 || (nYear % 400) == 0);
}
inline int DaysInMonth(int nMonth, BOOL bLeapYear)
{
static int nDaysInMonth[] =
{
31, 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31
};
return (nMonth == 2 && bLeapYear) ? 29 : nDaysInMonth[nMonth - 1];
}
inline int DaysInYear(int nYear)
{
return IsLeapYear(nYear) ? 366 : 365;
}
```