VC中两种可用的时间表达方式
在VC可以用的时间表示方式中,CRT和Win API分别维护了两种变量类型。
在CRT中,一种是数值格式time_t,它以一个整数值记录了从1970年1月1号0点经过的秒数。一种是易读格式tm。tm struct的格式是:
struct tm {
int tm_sec; /* seconds after the minute - [0,59] */
int tm_min; /* minutes after the hour - [0,59] */
int tm_hour; /* hours since midnight - [0,23] */
int tm_mday; /* day of the month - [1,31] */
int tm_mon; /* months since January - [0,11] */
int tm_year; /* years since 1900 */
int tm_wday; /* days since Sunday - [0,6] */
int tm_yday; /* days since January 1 - [0,365] */
int tm_isdst; /* daylight savings time flag */
};
int tm_sec; /* seconds after the minute - [0,59] */
int tm_min; /* minutes after the hour - [0,59] */
int tm_hour; /* hours since midnight - [0,23] */
int tm_mday; /* day of the month - [1,31] */
int tm_mon; /* months since January - [0,11] */
int tm_year; /* years since 1900 */
int tm_wday; /* days since Sunday - [0,6] */
int tm_yday; /* days since January 1 - [0,365] */
int tm_isdst; /* daylight savings time flag */
};
Win API中维护的时间变量类型和CRT中非常类似,只是表达稍有不同。其数字格式是FILETIME,它以一个64位数值记录了从1601年1月1号0点以来经过的100-nanosecond(1/10000000秒)数。易读格式是SYSTEMTIME,SYSTEMTIME sturct的格式是:
struct SYSTEMTIME {
WORD wYear;
WORD wMonth;
WORD wDayOfWeek;
WORD wDay;
WORD wHour;
WORD wMinute;
WORD wSecond;
WORD wMilliseconds;
};
WORD wYear;
WORD wMonth;
WORD wDayOfWeek;
WORD wDay;
WORD wHour;
WORD wMinute;
WORD wSecond;
WORD wMilliseconds;
};
因为我找不到tm struct到time_t的转化方法,作为折衷,我在自己的程序中一般采用Win API的时间表达方式。下面给出一个Yesterday()函数,虽然不会有很多人用到,但是里面给出了SYSTEMTIME和FILETIME相互转化的应用。以及在FILETIME中使用加减法的方法。
#include
<windows.h>
UINT64 S_Interval = 10000000;
UINT64 M_Interval = 60 * S_Interval;
UINT64 H_Interval = 60 * M_Interval;
UINT64 D_Interval = 24 * H_Interval;
SYSTEMTIME Yesterday(const SYSTEMTIME& InDay)
{
SYSTEMTIME Result;
FILETIME tmpFT;
SystemTimeToFileTime(&InDay, &tmpFT);
ULARGE_INTEGER ULI_Time;
ULI_Time.HighPart = tmpFT.dwHighDateTime;
ULI_Time.LowPart = tmpFT.dwLowDateTime;
ULI_Time.QuadPart -= D_Interval;
tmpFT.dwHighDateTime = ULI_Time.HighPart;
tmpFT.dwLowDateTime = ULI_Time.LowPart;
FileTimeToSystemTime(&tmpFT, &Result);
return Result;
}
添加一个调用方法:
#include
<iostream>
using
namespace std;
void
main()
{
SYSTEMTIME CurTime;
GetLocalTime(&CurTime);
for(SYSTEMTIME InDay = CurTime; InDay.wMonth != 12; InDay = Yesterday(InDay))
cout << InDay.wMonth << "/t" << InDay.wDay << endl;
}