All I want is to get the time since epoch in milliseconds and store it in an unsigned long.
I found this related question. But honestly, this can't be the easiest way to perform such a simple task, is it? I am hoping for something much simpler, but can't find anything in the std::chrono reference. Any advice is most welcome. I don't necessarily have to use std::chrono, but I want it to be platform independent.
std::chrono::system_clock::now Returns a time point representing with the current point in time.
In a computing context, an epoch is the date and time relative to which a computer's clock and timestamp values are determined. The epoch traditionally corresponds to 0 hours, 0 minutes, and 0 seconds (00:00:00) Coordinated Universal Time (UTC) on a specific date, which varies from system to system.
unsigned long milliseconds_since_epoch = std::chrono::system_clock::now().time_since_epoch() / std::chrono::milliseconds(1); although, especially since you want platform independence, it might be better to replace unsigned long with a type that's more likely to be large enough:
(unsigned) long longstd::(u)int64_tstd::chrono::milliseconds::repautoTo me, this clearly states both that you're risking loss of precision (by analogy with integer division) and that you're leaving the safety of the type system (by dividing by a typed time to give a unitless number). However, as demonstrated in the comments, some people would say that any attempt to move away from type-safety should be accompanied by a deliberate attempt to make the code look dangerous. If you need to deal with people who hold that belief, it might be simpler to use duration_cast rather than enter into an argument about irrelevant stylistic choices:
unsigned long milliseconds_since_epoch = std::chrono::duration_cast<std::chrono::milliseconds> (std::chrono::system_clock::now().time_since_epoch()).count();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With