Search code examples
datetimewinapimfcwmi

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


I am creating a windows application in C++ to obtain system boot time. I got that using wmi query ,but it is in the format "20140408141835.999999+480". I need to convert it into %d-%m-%Y %H:%M:%S format. I know in C# we have ManagementDateTimeConverter.ToDateTime(); method. But I need a solution in C++.


Solution

  • You can use the SWbemDateTime object as explained here: https://devblogs.microsoft.com/oldnewthing/20121102-00/?p=6183

    Here is the relevant piece of code:

    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;
    }
    

    Another solution is to port the .NET source to C++, since .NET is open source https://referencesource.microsoft.com/#System.Management/ManagementDatetime.cs,45057a40319a1c83