ARJUN
ARJUN

Reputation: 59

How to Convert Filetime to Datetime in C++ (MFC/Win32)

I am trying to get Windows boot up time using WMI query and got it as CIM_DATETIME format. I converted it into File time .The value I get form it is 132372033265000000. I need to convert it in to Date time(Sunday, June 21, 2020 8:55:27am). I found many solutions in C# but couldn't able to find one in C++.

Upvotes: 0

Views: 5223

Answers (2)

Strive Sun
Strive Sun

Reputation: 6299

To convert a FILETIME structure into a time that is easy to display to a user, use the FileTimeToSystemTime function.

Code Sample:

#include <Windows.h>
#include <iostream>

int main()
{    
    const char *day[] = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"};
    const char* month[] = {"January","February","March","April","May","June","July", "August","September","October","November","December"};
    long long value = 132372033265000000;
    FILETIME ft = { 0 };

    ft.dwHighDateTime = (value & 0xffffffff00000000) >> 32;
    ft.dwLowDateTime = value & 0xffffffff;

    SYSTEMTIME sys = { 0 };
    FileTimeToSystemTime(&ft, &sys);

    std::cout << day[sys.wDayOfWeek] << "," << month[sys.wMonth] << " " << sys.wDay << "," << sys.wYear << " "<< sys.wHour << ":" << sys.wMinute << ":" << sys.wSecond;

    return 0;
}

Output:

Sunday,July 21,2020 8:55:26

Upvotes: 1

bobk
bobk

Reputation: 13

Here is a solution that takes the current locale into account. I takes a SYSTEMTIME but you can easily convert that from a FILETIME:

CString DateTimeStr(const SYSTEMTIME *pST, bool bSeconds, bool bDate, bool bTime, bool bLongDate, bool bMilliSec, LCID Locale)
{
    CString sDate, sTime;
    DWORD dwFlags;
    int iStrLen;
    LPTSTR pBuf;

    if (bDate)
    {
        dwFlags = 0;
        if (bLongDate)
            dwFlags |= DATE_LONGDATE;
        else
            dwFlags |= DATE_SHORTDATE;
        iStrLen = GetDateFormat(Locale, dwFlags, pST, NULL, NULL, 0);
        pBuf = sDate.GetBuffer(iStrLen + 2);
        (void)GetDateFormat(Locale, dwFlags, pST, NULL, pBuf, iStrLen+2);
        sDate.ReleaseBuffer();
    }
    if (bTime)
    {
        dwFlags = 0;
        if (!bSeconds)
            dwFlags |= TIME_NOSECONDS;
        iStrLen = GetTimeFormat(Locale, dwFlags, pST, NULL, NULL, 0);
        pBuf = sTime.GetBuffer(iStrLen + 2);
        (void)GetTimeFormat(Locale, dwFlags, pST, NULL, pBuf, iStrLen+2);
        sTime.ReleaseBuffer();
        if (bMilliSec)
            sTime += _T(" ") + FmtNum(pST->wMilliseconds, 3, true) + TEXT(" ms");
    }
    if (bDate && bTime)
        return sDate + _T(" ") + sTime;
    if (bDate)
        return sDate;
    if (bTime)
        return sTime;
    return (_T(""));
}

Upvotes: 1

Related Questions