Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most elegant way to combine chrono::time_point from hours, minutes, seconds etc

Tags:

c++

c++11

chrono

I have a "human readable" variables hours, minutes, seconds, day, month, year that contains values corresponding to their names (let's say I have SYSTEMTIME structure from <windows.h>).
The only way I found to create a chrono::time_point is:

SYSTEMTIME sysTime = ...; // Came from some source (file, network, etc. )
tm t;
t.tm_sec = sysTime.wSecond;
t.tm_min = sysTime.wMinute;
t.tm_hour = sysTime.wHour;
t.tm_mday = sysTime.wDay;
t.tm_mon = sysTime.wMonth - 1;
t.tm_year = sysTime.wYear - 1900;
t.tm_isdst = 0;
std::chrono::system_clock::time_point dateTime =
    std::chrono::system_clock::from_time_t( mktime( & t ) );

First, I lost a milliseconds from SYSTEMTIME.
Second, (mmm...) I don't like this sort of conversion ))

Could you give a more elegant way to do this issue ?

like image 571
borisbn Avatar asked Jul 08 '15 06:07

borisbn


1 Answers

Using this open source, header-only library, I can:

#include "date.h"
#include <iostream>

struct SYSTEMTIME
{
    int wMilliseconds;
    int wSecond;
    int wMinute;
    int wHour;
    int wDay;
    int wMonth;
    int wYear;
};

int
main()
{
    SYSTEMTIME sysTime = {123, 38, 9, 10, 8, 7, 2015};
    std::chrono::system_clock::time_point dateTime =
        date::sys_days(date::year(sysTime.wYear)
                      /date::month(sysTime.wMonth)
                      /date::day(sysTime.wDay))
        + std::chrono::hours(sysTime.wHour)
        + std::chrono::minutes(sysTime.wMinute)
        + std::chrono::seconds(sysTime.wSecond)
        + std::chrono::milliseconds(sysTime.wMilliseconds);
    std::cout << dateTime << '\n';
}

which outputs:

2015-07-08 10:09:38.123000

In "date.h", you may have to play around with these macros to get things to compile with VS.:

#  define CONSTDATA const
#  define CONSTCD11 
#  define CONSTCD14

With a std-conforming C++14 compiler, these macros should be set to:

#  define CONSTDATA constexpr
#  define CONSTCD11 constexpr 
#  define CONSTCD14 constexpr
like image 102
Howard Hinnant Avatar answered Sep 20 '22 12:09

Howard Hinnant