WinRT使用DateTimeFormatter类将时间戳转换为可读的日期。在C++CX中,您将传递给它一个DateTime实例,其中包含UTC时间中的时间戳,并让它发挥它的魔力。
但是,我有一个在本地时间使用时间戳的应用程序。我想格式化它们并将它们显示给我的用户,但是如果我按原样传递时间戳,DateTimeFormatter将假设它是UTC,并尝试再次将其转换为本地时间,从而导致不正确的时间。
如何用WinRT显示本地时间?有没有办法把当地时间倒转到协调世界时?
时间戳是从消耗时间戳的机器生成的,因此不存在时区混淆的风险。生产UTC时间戳在技术上也是可行的,但这将是相当不方便的,我想回到这一点,只有当它是唯一的方式。
发布于 2014-07-04 21:16:18
谢天谢地,FileTimeToSystemTime、TzSpecificLocalTimeToSystemTime和SystemTimeToFileTime都适用于Windows应用程序。有了它,就可以创建一个函数来将本地更改为UTC。
uint64 LocalTimeToUtcTime(uint64 local)
{
LARGE_INTEGER largeTime;
largeTime.QuadPart = local;
FILETIME intermediate;
intermediate.dwHighDateTime = largeTime.HighPart;
intermediate.dwLowDateTime = largeTime.LowPart;
SYSTEMTIME systemLocal, systemUtc;
if (!FileTimeToSystemTime(&intermediate, &systemLocal))
{
// handle error
}
if (!TzSpecificLocalTimeToSystemTime(nullptr, &systemLocal, &systemUtc))
{
// handle error
}
if (!SystemTimeToFileTime(&systemUtc, &intermediate))
{
// handle error
}
largeTime.HighPart = intermediate.dwHighDateTime;
largeTime.LowPart = intermediate.dwLowDateTime;
return largeTime.QuadPart;
}发布于 2014-07-05 02:17:15
您可以使用Windows::Globalization::Calendar类处理本地时间或任何时区中的时间。
如果没有显式设置本地时区,则Calendar默认为本地时区。然后可以使用GetDateTime()检索可以与DateTimeFormatter一起使用的Windows::Foundation::DateTime实例。
Calendar^ cal = ref new Calendar();
cal->SetToMin();
cal->Year = 2014;
cal->Month = 7;
cal->Day = 14;
cal->Hour = 12;
cal->Minute = 34;
cal->Second = 56;
DateTime dt = cal->GetDateTime();
DateTimeFormatter^ dtf = ref new DateTimeFormatter("shortdate shorttime");
String^ result = dtf->Format(dt);
Logger::WriteMessage(result->Data());https://stackoverflow.com/questions/24580606
复制相似问题