C++ Converting a Datetime String to Epoch Cleanly

后端 未结 3 610
余生分开走
余生分开走 2020-12-19 04:07

Is there a C/C++/STL/Boost clean method to convert a date time string to epoch time (in seconds)?

yyyy:mm:dd hh:mm:ss
3条回答
  •  [愿得一人]
    2020-12-19 04:24

    On Windows platform you can do something like this if don't want to use Boost:

    // parsing string
    SYSTEMTIME stime = { 0 };
    sscanf(timeString, "%04d:%02d:%02d %02d:%02d:%02d",
           &stime.wYear, &stime.wMonth,  &stime.wDay,
           &stime.wHour, &stime.wMinute, &stime.wSecond);
    
    // converting to utc file time
    FILETIME lftime, ftime;
    SystemTimeToFileTime(&stime, &lftime);
    LocalFileTimeToFileTime(&lftime, &ftime);
    
    // calculating seconds elapsed since 01/01/1601
    // you can write similiar code to get time elapsed from other date
    ULONGLONG elapsed = *(ULONGLONG*)&ftime / 10000000ull;
    

    If you prefer standard library, you can use struct tm and mktime() to do the same job.

提交回复
热议问题