|
Boost Users : |
Subject: Re: [Boost-users] convert separate year, month, day, hour, minute, secs, ms to milliseconds since epoch
From: Leon Mlakar (leon_at_[hidden])
Date: 2019-03-04 23:51:40
On 05.03.2019 00:40, Leon Mlakar wrote:
> On 04.03.2019 23:17, Gavin Lambert via Boost-users wrote:
>> On 4/03/2019 09:45, Victor Yankee wrote:
>>> I am using C++14 and boost 1.64.0 (could move to newest boost), and
>>> need to convert date and time pieces to a single value for
>>> milliseconds since the epoch. This is what I have:
>>>
>>> int64_t msSinceEpoch(int year,int month,int day,int hour,int
>>> minute,int second,int ms)
>>> Â Â Â Â Â Â Â Â Â Â Â Â {
>>> Â Â Â Â Â Â Â Â Â Â Â Â struct std::tm t;
>>>             t.tm_sec   = second;
>>>             t.tm_min   = minute;
>>>             t.tm_hour  = hour;
>>>             t.tm_mday  = day;
>>>             t.tm_mon   = month-1;
>>>             t.tm_year  = year-1900;
>>>             t.tm_isdst = 0;
>>> Â Â Â Â Â Â Â Â Â Â Â Â return (1000* timegm(&t))+ms; // is timegm cross-platform?
>>> Â Â Â Â Â Â Â Â Â Â Â Â }
>>
>> timegm is not cross platform. mktime is, but uses local time instead
>> of UTC.
>>
>>> Is there a better way? Could not figure out how to use boost::chrono
>>> :( Something else?
>>
>> Boost.Chrono is for time intervals, not dates.
>>
>> Boost.DateTime, however, has the ptime class which will solve this
>> for you.
>
> I think with C++11 something like:
>
> std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count()
>
>
> might also do the trick.
>
> Cheers,
>
> Leon
Err, then again, it might not until C++20. C++11 embarrassingly failed
to state what the Epoch is. So for now clocks are free to use their own
and currently the above is useless for cross-platform applications (but
so is timegm). I wonder how this works on Windows with VS2019?
Cheers,
Leon
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net