Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert number of seconds to time

Tags:

c++

datetime

time

Is there a way to convert the number of seconds (e.g. 3056144 sec, this is time delta not a time) to time in format YYYY-mm-dd HH:MM:SS?

I've tried to convert number of seconds to struct tm using localtime and then substract UNIX start time (1970-01-01), but this is not working as expected.

Thanks in advance.

P.S. I have to use C++03, not C++11.

like image 932
maverik Avatar asked Jul 29 '14 14:07

maverik


1 Answers

If using Boost.Date_Time is an option for you, this might be what you're looking for:

#include <boost/date_time.hpp>

using boost::posix_time::seconds;
using boost::posix_time::to_simple_string;

std::cout << to_simple_string(seconds(3056144)) << std::endl;

This will print:

848:55:44

However, as you can see in the output above, it will not tell you how many years have passed. This is for good reason, because a year has not always 365 days.

like image 193
Alexander Tobias Bockstaller Avatar answered Sep 30 '22 11:09

Alexander Tobias Bockstaller