如何将使用WMI查询获得的CIM_DATETIME格式转换为C++中的本地时间(MFC/Win32)

How to convert CIM_DATETIME format that obtained using WMI Queries into local time in C++(MFC/Win32)

我正在用 C++ 创建一个 windows 应用程序来获取系统启动时间。 我使用 wmi 查询得到了它,但它的格式是“20140408141835.999999+480”。 我需要将它转换成 %d-%m-%Y %H:%M:%S 格式。 我知道在 C# 中我们有 ManagementDateTimeConverter.ToDateTime();方法。 但我需要一个 C++ 的解决方案。

您可以使用 SWbemDateTime object as explained here: https://devblogs.microsoft.com/oldnewthing/20121102-00/?p=6183

相关代码如下:

BOOL FileTimeFromCIMDateTime(__in LPCWSTR psz, __out LPFILETIME pft)
{
 BOOL fSuccess = FALSE;
 ISWbemDateTime *pDateTime;
 HRESULT hr = CoCreateInstance(__uuidof(SWbemDateTime), 0,
                 CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pDateTime));
 if (SUCCEEDED(hr)) {
  BSTR bstr = SysAllocString(psz);
  if (bstr) {
   hr = pDateTime->put_Value(bstr);
   if (SUCCEEDED(hr)) {
    BSTR bstrFT;
    hr = pDateTime->GetFileTime(VARIANT_FALSE, &bstrFT);
    if (SUCCEEDED(hr)) {
     __int64 i64FT = _wtoi64(bstrFT);
     pft->dwLowDateTime = LODWORD(i64FT);
     pft->dwHighDateTime = HIDWORD(i64FT);
     fSuccess = TRUE;
     SysFreeString(bstrFT);
    }
   }
   SysFreeString(bstr);
  }
  pDateTime->Release();
 }
 return fSuccess;
}

另一种解决方案是将 .NET 源代码移植到 C++,因为 .NET 是开源的 https://referencesource.microsoft.com/#System.Management/ManagementDatetime.cs,45057a40319a1c83