Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ function that converts time(NULL) to local time

Tags:

c++

function

time

In C++ I'm writing a function that converts time(NULL), which is all the seconds since January 1, 1970 in UTC time, to local time EST in military time format (hours:minutes:seconds). I'm honestly stumped how to mathematically do this so that the program stays accurate as time moves forward.

Also I'm well aware that there is a local time function but I'd like to build this function from the ground up. Does anyone have any advice or tips?

like image 846
Adam Jensen Avatar asked Mar 19 '26 01:03

Adam Jensen


1 Answers

Also I'm well aware that there is a local time function but I'd like to build this function from the ground up. Does anyone have any advice or tips?

Why would you want to do this when there are plenty of free and well-tested packages? As mentioned in the comments, getting daylight savings time correct is non-trivial. Existing packages do just that, and they do it right, based on the IANA tzinfo database.

C options:

  • std::localtime(). This function uses a global variable; it is not thread safe.

  • localtime_r(). This is a POSIX function and is not a part of the C++ library. It does not exist on Windows.

  • localtime_s(). This is an optional C11 function. Even if it exists on your machine, it might not be a part of <ctime>.

C++ options:

  • Boost Date-Time, https://github.com/boostorg/date_time .

  • Howard Hinant's date-time module, https://github.com/HowardHinnant/date .

like image 178
David Hammen Avatar answered Mar 20 '26 14:03

David Hammen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!