在Windows平台上,可以使用API函数GetLocalTime或localtime来获取当前日期和时间。这些函数需要包含windows.h头文件。
经过多次修改时区测试使用GetLocalTime获取到的最精准,以下为示例代码
std::wstring GetFormatTime()
{
SYSTEMTIME time;
GetLocalTime(&time);
TIME_ZONE_INFORMATION tzi;
GetSystemTime(&tzi.StandardDate);
GetTimeZoneInformation(&tzi);
int zone = tzi.Bias / -60;
TCHAR buf[100] = { 0 };
if (zone < 0)
wsprintf(buf, L"%d-%02d-%02d %02d:%02d:%02d%02d:00", time.wYear, time.wMonth, time.wDay, time.wHour, time.wMinute, time.wSecond, zone);
else
wsprintf(buf, L"%d-%02d-%02d %02d:%02d:%02d+%02d:00", time.wYear, time.wMonth, time.wDay, time.wHour, time.wMinute, time.wSecond, zone);
return buf;
}
int main()
{
wstring strtime = GetFormatTime();
return 0
}