Convert UTC time_t to UTC tm - c++

All my internal times are UTC stored in time_t. I need to convert them to struct tm. If I use localtime the time is correct, except that tm_isdst may be set resulting in the time being off an hour. If I use gmtime it gets the wrong time, off by the time zone difference.
Edit I am looking for a cross platform solution that works in Windows and Linux

Here is a cross platform solution that requires C++11 or better, and a free, open-source, header-only date library. And when your vendor brings you C++20, you can loose the date library as it is incorporated into C++20 <chrono>.
It is actually easier to convert from time_t to a UTC tm by going through <chrono> than it is to use the C API. There do exist various extensions to do this on each platform, but the extensions have different syntaxes. This solution has a uniform syntax across all platforms.
In C++11, though not specified, it is a de-facto standard that both time_t and std::chrono::system_clock track Unix Time, though at different precisions. In C++20 this becomes specified for std::chrono::system_clock. For time_t the de-facto precision is seconds. One can take advantage of this knowledge to create extremely efficient conversions between the C API and the C++ <chrono> API.
Step 1: Convert time_t to a chrono::time_point
This is very easy and efficient:
date::sys_seconds
to_chrono(std::time_t t)
{
using namespace date;
using namespace std::chrono;
return sys_seconds{seconds{t}};
}
date::sys_seconds is simply a type alias for:
std::chrono::time_point<std::chrono::system_clock, std::chrono::seconds>
I.e. a time_point based on system_clock but with seconds precision.
All this function does is change type from time_t to seconds and then to time_point. No actual computation is done. Here is an optimized clang compilation of to_chrono:
.globl __Z9to_chronol ## -- Begin function _Z9to_chronol
.p2align 4, 0x90
__Z9to_chronol: ## #_Z9to_chronol
.cfi_startproc
## %bb.0:
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset %rbp, -16
movq %rsp, %rbp
.cfi_def_cfa_register %rbp
movq %rdi, %rax
popq %rbp
retq
.cfi_endproc
All that's there is the boiler plate for a function call. And if you inline this, even that disappears.
Furthermore this function will port to C++20 by simply removing using namespace date and changing date::sys_seconds to std::chrono::sys_seconds.
Step 2: Convert sys_seconds to a tm
This is where the computation happens:
std::tm
to_tm(date::sys_seconds tp)
{
using namespace date;
using namespace std::chrono;
auto td = floor<days>(tp);
year_month_day ymd = td;
hh_mm_ss<seconds> tod{tp - td}; // <seconds> can be omitted in C++17
tm t{};
t.tm_sec = tod.seconds().count();
t.tm_min = tod.minutes().count();
t.tm_hour = tod.hours().count();
t.tm_mday = unsigned{ymd.day()};
t.tm_mon = (ymd.month() - January).count();
t.tm_year = (ymd.year() - 1900_y).count();
t.tm_wday = weekday{td}.c_encoding();
t.tm_yday = (td - sys_days{ymd.year()/January/1}).count();
t.tm_isdst = 0;
return t;
}
All of the computation happens in the first three lines:
auto td = floor<days>(tp);
year_month_day ymd = td;
hh_mm_ss<seconds> tod{tp - td}; // <seconds> can be omitted in C++17
Then the rest of the function just extracts the fields to fill out the tm members.
auto td = floor<days>(tp);
The first line above simply truncates the precision of the time_point from seconds to days, rounding down towards negative infinity (even for time_points prior to the 1970-01-01 epoch). This is little more than a divide by 86400.
year_month_day ymd = td;
The second line above takes the count of days since the epoch and converts it to a {year, month, day} data structure. This is where most of the computation happens.
hh_mm_ss<seconds> tod{tp - td}; // <seconds> can be omitted in C++17
The third line above subtracts the days-precision time_point from the seconds-precision time_point resulting in a std::chrono::seconds time duration since midnight UTC. This duration is then broken out into a {hours, minutes, seconds} data structure (the type hh_mm_ss). In C++17 this line can optionally be simplified to:
hh_mm_ss tod{tp - td}; // <seconds> can be omitted in C++17
Now to_tm simply extracts the fields to fill out the tm according to the C API.
int tm_sec; // seconds after the minute -- [0, 60]
int tm_min; // minutes after the hour -- [0, 59]
int tm_hour; // hours since midnight -- [0, 23]
int tm_mday; // day of the month -- [1, 31]
int tm_mon; // months since January -- [0, 11]
int tm_year; // years since 1900
int tm_wday; // days since Sunday -- [0, 6]
int tm_yday; // days since January 1 -- [0, 365]
int tm_isdst; // Daylight Saving Time flag
It is important to first zero-initialize the tm because different platforms have extra tm data members as extensions that are best given the value 0.
tm t{};
For the hours, minutes and seconds one simply extracts the appropriate chrono::duration from tod and then extracts the integral values with the .count() member function:
t.tm_sec = tod.seconds().count();
t.tm_min = tod.minutes().count();
t.tm_hour = tod.hours().count();
day has an explicit conversion to unsigned and this is one of the few places where the C API doesn't give a tm data member an unexpected bias:
t.tm_mday = unsigned{ymd.day()};
tm_mon is defined as "months since January" so that bias has to be taken into account. One can subtract January from the month, resulting in a months duration. This is a chrono::duration, and the integral value can be extracted with the .count() member function:
t.tm_mon = (ymd.month() - January).count();
Similarly, tm_year is years since 1900:
t.tm_year = (ymd.year() - 1900_y).count();
One can convert a days-precision time_point (td) to a weekday with conversion syntax, and then weekday has a member function .c_encoding() to extract an integral value which matches the C API: days since Sunday -- [0, 6]. Alternatively there is also a .iso_encoding() member function if one desires the ISO encoding [Mon, Sun] -> [1, 7].
t.tm_wday = weekday{td}.c_encoding();
tm_yday is days since January 1 -- [0, 365]. This is easily computed by subtracting the first of the year from the days-precision time_point (td), creating a days chrono::duration:
t.tm_yday = (td - sys_days{ymd.year()/January/1}).count();
Finally tm_isdst should be set to 0 to indicate Daylight Saving Time is not in effect. Technically this step was already done when zero-initializing tm, but is repeated here for readability purposes:
t.tm_isdst = 0;
to_tm can be ported to C++20 by:
remove using namespace date;
change date::sys_seconds to std::chrono::sys_seconds
change 1900_y to 1900y
Example Use:
Given a time_t, here is how you can use these functions to convert it to a UTC tm:
std::time_t t = std::time(nullptr);
std::tm tm = to_tm(to_chrono(t));
Here are the necessary headers:
#include "date/date.h"
#include <chrono>
#include <ctime>
Or in C++20, just:
#include <chrono>
#include <ctime>

Related

Seconds since Epoch to formatted time [duplicate]

How can I convert number of seconds since 1970 to DateTime in c++?
I am getting the time in the below format:
1296575549:573352
The left part of the colon is in seconds and the right part in micro seconds.
Please help.
Thanks,
Syd
Try and use gmtime() (see http://www.cplusplus.com/reference/clibrary/ctime/gmtime/) or localtime() to convert a time_t to a struct tm
Use boost::Date_Time to do this. Code below assumes _interval is number of seconds since 1970. Note this code example doesn't handle the micro-second portion, but I am sure it could be modified to do so.
#include <boost/date_time/gregorian/gregorian_types.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
double interval(1296575549.0f);
boost::posix_time::ptime m_DateTime = ptime(date(1970, 1, 1),
time_duration(0, 0, 0,
time_duration::ticks_per_second() *
(time_duration::fractional_seconds_type)_interval));
Three important things about converting time using C/C++ library.
gmtime() or localtime() from standard library convert from time_t to struct tm, but the resolution for time_t is seconds from epoch. So fractional seconds will not count.
mktime() converts backwards from struct tm to time_t, but it will return -1 if the input date is out of range. (Reference: year 2038 problem)
If you are not using 64bit timestamp, even you run programs on 64bit machines, you still have year 2038 problem. There are 64bit version functions like gmtime64(), localtime64(), mktime64() that may resolve the year out of range issue. (Reference)
New answer for a very old question. Rationale: Better tools.
Starting in C++11, one can easily store this quantity in a std::chrono::system_clock::time_point:
#include <chrono>
#include <iostream>
#include <sstream>
int
main()
{
using namespace std;
using namespace std::chrono;
istringstream in{"1296575549:573352"};
long si, usi;
char sep;
in >> si >> sep >> usi;
system_clock::time_point tp{seconds{si} + microseconds{usi}};
}
Though the epoch of system_clock is unspecified in C++11, every implementation is tracking Unix Time (time since 1970-01-01 00:00:00 UTC, excluding leap seconds). Different implementations will have different precisions for system_clock::time_point, but you don't really have to care about that when converting into system_clock::time_point as shown above. The <chrono> library will just do the right thing.
Starting in C++20 the Unix Time measure of system_clock::time_point will be specified, and you will be able to stream it out in a human readable form:
cout << tp << '\n';
For this example that will output:
2011-02-01 15:52:29.573352
On some platforms there may be a few trailing zeroes on this output, depending on the precision of system_clock::time_point on that platform. This is a UTC date/time. There will also be ways to convert this to a particular time zone if desired (in C++20).
You can experiment with this part of C++20 today by using Howard Hinnant's date/time library. This will require an additional #include "date/date.h" ("date/tz.h" for time zone functionality), and a using namespace date; to enable the system_clock::time_point streaming operator.
If it is known that your count of seconds includes leap seconds (Unix Time stamps don't), C++20 also provides a way to deal with that:
Just change system_clock to utc_clock in the above example and the new output will be:
2011-02-01 15:52:05.573352
which accounts for the 24 leap seconds inserted prior to this date.
As an example of duration available in seconds, let's assume you want to have an idea of the running time of your program:
#include <ctime>
time_t startRawTime;
time( &startRawTime );
//...your program performs computations...
time_t endRawTime;
time( &endRawTime );
time_t elapsedSec = difftime( endRawTime, startRawTime );
// but elapsedSec can be any duration, e.g. 3734, as long as it is in seconds
tm * ptm = gmtime( &elapsedSec );
printf( "elapsed time: %02dh %02dm %02ds\n",
ptm->tm_hour,
ptm->tm_min,
ptm->tm_sec );
You would get something like this for instance:
elapsed time: 01h 02m 14s
Well, the most complex case:
86'400 s/day
31'557'600 s/year (365.25 d)
1296575549/31557600 = 41 years
1296575549-41*31557600 = 2'713'949 s
2713949/86400 ==> 31 d
2713949-31*86400 =35'549
35549/(60*60) = 9h
35549-9*60*60 = 3'149
3'149/(60*60) = 0h
3'149- 0* (60*60) = 3'149
3149/60 = 52 m
3149-52*60 = 29s
--> year = 1970 + 41
--> month = 1 + 0
--> day = 31 (+1?)
--> Time 00:52:29
==> 2011, Jan 31, 00:52:29 GMT
To calculate the month from the day, you need to copy paste an isLeapYear function, because of February.
Hmm, looks like one also needs to account for the leap years until last leap year, which were subtracted in surplus. Hmm, effects of daylight saving time...
Go sleep !

Alternative to timegm on Solaris

I have a program that was originally written for Linux, but I now have a requirement to get it running on Solaris 10.
Part of this program uses the timegm function to convert a struct tm into a time_t epoch seconds value. The input time is referenced to UTC.
Trying to compile this program on Solaris, it fails because timegm cannot be found. After some googling I realized that this function has been removed from Solaris a long time ago (and even the Linux manpage recommends against using it, because it isn't standardized).
However I have so far not been able to find an alternative function, that takes a struct tm referenced to UTC and converts to epoch time. Most references I found on the net recommend using mktime, however that function interprets the inputs with reference to the system local time zone.
Note that I do not wish to use tzset to force the timezone to UTC, as that would have other side effects on the program.
So my question is: how can I convert a struct tm broken down time value, expressed with respect to UTC, into an epoch time, in the absence of timegm?
The program is written in C++ so I'm not limited to C solutions, although I would prefer not to embark on a wholesale rewrite to use some additional time library.
You could use days_from_civil which is described here in detail
// Returns number of days since civil 1970-01-01. Negative values indicate
// days prior to 1970-01-01.
// Preconditions: y-m-d represents a date in the civil (Gregorian) calendar
// m is in [1, 12]
// d is in [1, last_day_of_month(y, m)]
// y is "approximately" in
// [numeric_limits<Int>::min()/366, numeric_limits<Int>::max()/366]
// Exact range of validity is:
// [civil_from_days(numeric_limits<Int>::min()),
// civil_from_days(numeric_limits<Int>::max()-719468)]
template <class Int>
constexpr
Int
days_from_civil(Int y, unsigned m, unsigned d) noexcept
{
static_assert(std::numeric_limits<unsigned>::digits >= 18,
"This algorithm has not been ported to a 16 bit unsigned integer");
static_assert(std::numeric_limits<Int>::digits >= 20,
"This algorithm has not been ported to a 16 bit signed integer");
y -= m <= 2;
const Int era = (y >= 0 ? y : y-399) / 400;
const unsigned yoe = static_cast<unsigned>(y - era * 400); // [0, 399]
const unsigned doy = (153*(m + (m > 2 ? -3 : 9)) + 2)/5 + d-1; // [0, 365]
const unsigned doe = yoe * 365 + yoe/4 - yoe/100 + doy; // [0, 146096]
return era * 146097 + static_cast<Int>(doe) - 719468;
}
to convert the {year, month, day} triple in the tm to a count of days since the epoch (1970-01-01). Be careful when converting these fields from tm for their eccentricities (e.g. tm_year + 1900).
Multiply this count of days by 86400 and add to that the {hours, minutes, seconds} data from the tm (each converted to seconds).
And you're done. Don't worry about leap seconds, timegm didn't worry about them either. If you're really concerned about leap seconds I have a C++11/14 solution available to deal with that, but I'm guessing that is more than you want to get into.
Don't be put off by the C++14 syntax shown above. It is trivial to convert this algorithm to C (or any other language for that matter).
Per the POSIX standard for tzset():
SYNOPSIS
#include <time.h>
extern int daylight;
extern long timezone;
extern char *tzname[2];
void tzset(void);
...
The tzset() function also shall set the external variable daylight
to 0 if Daylight Savings Time conversions should never be applied for
the timezone in use; otherwise, non-zero. The external variable
timezone shall be set to the difference, in seconds, between
Coordinated Universal Time (UTC) and local standard time.
You should be able to call tzset() to set the value in timezone, then use mktime() to get the time in the current timezone, then apply the difference in the timezone variable to to the result from mktime() to convert that result to UTC.
I don't have access to Solaris right now to test that.

How to calculate time differences in C++ with time_t before the epoch?

What I would like to do with my simple program is to calculate a difference in seconds between two dates.
time_t referenceDate;
time_t dateNow = time(0);
struct tm referenceDateComponent = {0};
referenceDateComponent.tm_hour = 0;
referenceDateComponent.tm_min = 0;
referenceDateComponent.tm_sec = 0;
referenceDateComponent.tm_year = 89;
referenceDateComponent.tm_mon = 11;
referenceDateComponent.tm_mday = 31;
referenceDate = mktime(&referenceDateComponent);
long seconds = difftime(dateNow, referenceDate);
Whit the code above the application works fine, but if try to set tm.year negative (to build a date before 1900) the mktime() function return -1
I know that time_t type manage only dates starting from Jan 1, 1970 UTC according with the documentation:
For historical reasons, it is generally implemented as an integral value representing the number of seconds elapsed since 00:00 hours, Jan 1, 1970 UTC (i.e., a unix timestamp). Although libraries may implement this type using alternative time representations.
I know there are also the Boost libraries but is not a usable solution for me.
So my question would be, there is any way to get difference in seconds from dates starting before 1970?
I recommend using the C++11 std::chrono namespace and <chrono> standard headers and the standard functions and classes inside them.
You might also consider difftime from the C standard and localtime & mktime
And there are a lot of good other reasons to upgrade to C++11 at least (or C++14 if you can). Several good recent free software compilers GCC and Clang/LLVM support that standard (compile with -std=c++11 or -std=gnu++14 if you want GNU extensions & C++14)
BTW, your question is much more complex than you believe. Calendars has changed. Julian/Gregorian calendar transition happened in the XXth century in Russia. My late mother was born in 1919, during emigration and the civil war, in a Russian village whose legal system was disputed at that time (Russian revolution did not occur instantly). She had some papers mentioning 13th december 1919, and other papers mentioning 26th december 1919, referring to the same date in two different calendars. How would your software deal with that? I'm not even sure that timezone is enough!
BTW, I'm not sure that Boost or C++11 <chrono> can reliably deal with such calendar issues.
nwp mentioned in a comment a very good computerphile video: Problem with Time & Timezones.
You've already answered this question. time_t represents a number of seconds since the UNIX epoch, not number of seconds since some arbitrary time before that. What you are trying to do fundamentally makes no sense.
If you're stuck on C++03, regardless of your ambiguous claims about what you can and cannot use, you will have to use Boost.DateTime.
Otherwise, the standard library has some nice modern timekeeping features in <chrono>.
When you're trying to do calendar arithmetic using time_t, you naturally have to worry about the type and representation of time_t, which is of course implementation-defined. It's almost always a signed, integral type. On Unix and modern MacOS systems it's seconds since 1970, and for compatibility I think it might be used that way on Windows, too. It tends to be 32 bits. Putting that all together, it can typically represent dates between December 13, 1901 and January 18, 2038.
And indeed when I changed the tm_year line in your code to
referenceDateComponent.tm_year = 60;
the code worked and printed 1721200226, which is about 19921 days or 54.5 years, which is exactly the difference between December 31, 1960 and today.
But if you set tm_year to be negative, you'd be asking for a date before 1900, and that's not going to work using the typical definition of time_t we've been discussing.
(It's true there are other possibilities for time_t. It could be floating point. It could be unsigned instead of signed. It could be a 64-bit type, meaning it'd have a range of almost 600,000,000,000 years, which is incidentally more than a 32-bit tm_year can hold.)
So although there are several naysayers here telling you not to, and although there are certainly plenty of obscure difficulties having to do with time zones and leap seconds and calendars other than Gregorian, you can usually get away with using time_t to do basic calendar math for dates in the 20th century and in this century up until 2038, when the infamous "Y2.038K problem" is going to hit. (It will, I fear, be somewhat worse than the not-so-infamous Y2K problem, but that's another story.)
As I said, your code worked for me for dates before 1970. Here's what I'd recommend using for simple time_t-based date calculations (and with caveats as already mentioned):
time_t makedate(int year, int month, int day)
{
struct tm tm = {0};
tm.tm_hour = 12;
tm.tm_min = tm.tm_sec = 0;
tm.tm_year = year - 1900;
tm.tm_mon = month - 1;
tm.tm_mday = day;
tm.tm_isdst = -1;
return mktime(&tm);
}
int main()
{
long int d = difftime(makedate(2015, 7, 17), makedate(2015, 6, 1));
printf("%ld sec = %ld days = %.2f years\n", d, d/86400, d/86400./365.25);
d = difftime(makedate(2015, 7, 17), makedate(2014, 7, 17));
printf("%ld sec = %ld days = %.2f years\n", d, d/86400, d/86400./365.25);
d = difftime(makedate(1975, 7, 17), makedate(1965, 7, 17));
printf("%ld sec = %ld days = %.2f years\n", d, d/86400, d/86400./365.25);
d = difftime(makedate(1950, 1, 11), makedate(1925, 1, 1));
printf("%ld sec = %ld days = %.2f years\n", d, d/86400, d/86400./365.25);
d = difftime(makedate(2030, 12, 31), makedate(2025, 12, 31));
printf("%ld sec = %ld days = %.2f years\n", d, d/86400, d/86400./365.25);
}
Just like your code, this leverages the surprisingly powerful mktime function, and can do everything it can do. It handles leap years, no problem. It does not handle leap seconds or calendar changes.
And if, as you say, you're interested in dates before 1900, I'm afraid you're out of luck. time_t simply cannot represent those dates on most systems, so you're going to have to pursue some other solution.
You can use the Gregorian calendar's 400-year periodicity to work with dates before the Epoch. (Of course, you need to be careful about the start of the Gregorian calendar in your country of interest).
Add 400 years to both dates you're comparing so that they are beyond 1970 (the Epoch), normalize with mktime(), and compute the difference with difftime():
#include <time.h>
#include <stdio.h>
double compare_dates (const struct tm *date_1, const struct tm *date_2)
{
struct tm normalized_1 = *date_1, normalized_2 = *date_2;
normalized_1.tm_year += 400, normalized_2.tm_year += 400;
time_t t1 = mktime(&normalized_1);
time_t t2 = mktime(&normalized_2);
return difftime(t1, t2);
}
int main (void)
{
// how many seconds between June 1st 1880 and 15th September 1892 ?
struct tm june_1st_1880 = { .tm_mon = 6 - 1, .tm_mday = 1, .tm_year = 1880 - 1900 };
struct tm september_15th_1892 = { .tm_mon = 9 - 1, .tm_mday = 15, .tm_year = 1892 - 1900 };
printf("%f seconds", compare_dates(&june_1st_1880, &september_15th_1892));
}

How can I convert number of seconds since 1970 to DateTime in c++?

How can I convert number of seconds since 1970 to DateTime in c++?
I am getting the time in the below format:
1296575549:573352
The left part of the colon is in seconds and the right part in micro seconds.
Please help.
Thanks,
Syd
Try and use gmtime() (see http://www.cplusplus.com/reference/clibrary/ctime/gmtime/) or localtime() to convert a time_t to a struct tm
Use boost::Date_Time to do this. Code below assumes _interval is number of seconds since 1970. Note this code example doesn't handle the micro-second portion, but I am sure it could be modified to do so.
#include <boost/date_time/gregorian/gregorian_types.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
double interval(1296575549.0f);
boost::posix_time::ptime m_DateTime = ptime(date(1970, 1, 1),
time_duration(0, 0, 0,
time_duration::ticks_per_second() *
(time_duration::fractional_seconds_type)_interval));
Three important things about converting time using C/C++ library.
gmtime() or localtime() from standard library convert from time_t to struct tm, but the resolution for time_t is seconds from epoch. So fractional seconds will not count.
mktime() converts backwards from struct tm to time_t, but it will return -1 if the input date is out of range. (Reference: year 2038 problem)
If you are not using 64bit timestamp, even you run programs on 64bit machines, you still have year 2038 problem. There are 64bit version functions like gmtime64(), localtime64(), mktime64() that may resolve the year out of range issue. (Reference)
New answer for a very old question. Rationale: Better tools.
Starting in C++11, one can easily store this quantity in a std::chrono::system_clock::time_point:
#include <chrono>
#include <iostream>
#include <sstream>
int
main()
{
using namespace std;
using namespace std::chrono;
istringstream in{"1296575549:573352"};
long si, usi;
char sep;
in >> si >> sep >> usi;
system_clock::time_point tp{seconds{si} + microseconds{usi}};
}
Though the epoch of system_clock is unspecified in C++11, every implementation is tracking Unix Time (time since 1970-01-01 00:00:00 UTC, excluding leap seconds). Different implementations will have different precisions for system_clock::time_point, but you don't really have to care about that when converting into system_clock::time_point as shown above. The <chrono> library will just do the right thing.
Starting in C++20 the Unix Time measure of system_clock::time_point will be specified, and you will be able to stream it out in a human readable form:
cout << tp << '\n';
For this example that will output:
2011-02-01 15:52:29.573352
On some platforms there may be a few trailing zeroes on this output, depending on the precision of system_clock::time_point on that platform. This is a UTC date/time. There will also be ways to convert this to a particular time zone if desired (in C++20).
You can experiment with this part of C++20 today by using Howard Hinnant's date/time library. This will require an additional #include "date/date.h" ("date/tz.h" for time zone functionality), and a using namespace date; to enable the system_clock::time_point streaming operator.
If it is known that your count of seconds includes leap seconds (Unix Time stamps don't), C++20 also provides a way to deal with that:
Just change system_clock to utc_clock in the above example and the new output will be:
2011-02-01 15:52:05.573352
which accounts for the 24 leap seconds inserted prior to this date.
As an example of duration available in seconds, let's assume you want to have an idea of the running time of your program:
#include <ctime>
time_t startRawTime;
time( &startRawTime );
//...your program performs computations...
time_t endRawTime;
time( &endRawTime );
time_t elapsedSec = difftime( endRawTime, startRawTime );
// but elapsedSec can be any duration, e.g. 3734, as long as it is in seconds
tm * ptm = gmtime( &elapsedSec );
printf( "elapsed time: %02dh %02dm %02ds\n",
ptm->tm_hour,
ptm->tm_min,
ptm->tm_sec );
You would get something like this for instance:
elapsed time: 01h 02m 14s
Well, the most complex case:
86'400 s/day
31'557'600 s/year (365.25 d)
1296575549/31557600 = 41 years
1296575549-41*31557600 = 2'713'949 s
2713949/86400 ==> 31 d
2713949-31*86400 =35'549
35549/(60*60) = 9h
35549-9*60*60 = 3'149
3'149/(60*60) = 0h
3'149- 0* (60*60) = 3'149
3149/60 = 52 m
3149-52*60 = 29s
--> year = 1970 + 41
--> month = 1 + 0
--> day = 31 (+1?)
--> Time 00:52:29
==> 2011, Jan 31, 00:52:29 GMT
To calculate the month from the day, you need to copy paste an isLeapYear function, because of February.
Hmm, looks like one also needs to account for the leap years until last leap year, which were subtracted in surplus. Hmm, effects of daylight saving time...
Go sleep !

std::mktime and timezone info

I'm trying to convert a time info I reveive as a UTC string to a timestamp using std::mktime in C++. My problem is that in <ctime> / <time.h> there is no function to convert to UTC; mktime will only return the timestamp as local time.
So I need to figure out the timezone offset and take it into account, but I can't find a platform-independent way that doesn't involve porting the whole code to boost::date_time. Is there some easy solution which I have overlooked?
timestamp = mktime(&tm) - _timezone;
or platform independent way:
timestamp = mktime(&tm) - timezone;
If you look in the source of mktime() on line 00117, the time is converted to local time:
seconds += _timezone;
mktime() uses tzname for detecting timezone. tzset() initializes the tzname variable from the TZ enviroment variable. If the TZ variable appears in the enviroment but its value is empty or its value cannot be correctly interpreted, UTC is used.
A portable (not threadsafe) version according to the timegm manpage
#include <time.h>
#include <stdlib.h>
time_t
my_timegm(struct tm *tm)
{
time_t ret;
char *tz;
tz = getenv("TZ");
setenv("TZ", "", 1);
tzset();
ret = mktime(tm);
if (tz)
setenv("TZ", tz, 1);
else
unsetenv("TZ");
tzset();
return ret;
}
Eric S Raymond has a threadsafe version published in his article Time, Clock, and Calendar Programming In C
time_t my_timegm(register struct tm * t)
/* struct tm to seconds since Unix epoch */
{
register long year;
register time_t result;
#define MONTHSPERYEAR 12 /* months per calendar year */
static const int cumdays[MONTHSPERYEAR] =
{ 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
/*# +matchanyintegral #*/
year = 1900 + t->tm_year + t->tm_mon / MONTHSPERYEAR;
result = (year - 1970) * 365 + cumdays[t->tm_mon % MONTHSPERYEAR];
result += (year - 1968) / 4;
result -= (year - 1900) / 100;
result += (year - 1600) / 400;
if ((year % 4) == 0 && ((year % 100) != 0 || (year % 400) == 0) &&
(t->tm_mon % MONTHSPERYEAR) < 2)
result--;
result += t->tm_mday - 1;
result *= 24;
result += t->tm_hour;
result *= 60;
result += t->tm_min;
result *= 60;
result += t->tm_sec;
if (t->tm_isdst == 1)
result -= 3600;
/*# -matchanyintegral #*/
return (result);
}
I have this same problem yesterday and searching man mktime:
The functions mktime() and timegm() convert the broken-out time (in the structure pointed to by *timeptr) into a time value with the same encoding as that of the values returned by the time(3) function (that is, seconds from the Epoch, UTC). The mktime() function interprets the input structure according to the current timezone setting (see tzset(3)). The timegm() function interprets the input structure as representing Universal Coordinated Time (UTC).
In short:
You should use timegm(), instead of using mktime().
mktime assumes that the date value is in the local time zone. Thus you can change the timezone environment variable beforehand (setenv) and get the UTC timezone.
Windows tzset
Can also try looking at various home-made utc-mktimes, mktime-utcs, etc.
If you are trying to do this in a multithreaded program and don't want to deal with locking and unlocking mutexes (if you use the environment variable method you'd have to), there is a function called timegm that does this. It isn't portable, so here is the source:
http://trac.rtmpd.com/browser/trunk/sources/common/src/platform/windows/timegm.cpp
int is_leap(unsigned y) {
y += 1900;
return (y % 4) == 0 && ((y % 100) != 0 || (y % 400) == 0);
}
time_t timegm (struct tm *tm)
{
static const unsigned ndays[2][12] = {
{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
};
time_t res = 0;
int i;
for (i = 70; i < tm->tm_year; ++i)
res += is_leap(i) ? 366 : 365;
for (i = 0; i < tm->tm_mon; ++i)
res += ndays[is_leap(tm->tm_year)][i];
res += tm->tm_mday - 1;
res *= 24;
res += tm->tm_hour;
res *= 60;
res += tm->tm_min;
res *= 60;
res += tm->tm_sec;
return res;
}
Use _mkgmtime, it takes care of everything.
Here is a simple, tested, hopefully portable piece of code converting from struct tm to seconds since the beginning of an adjustable UTC year, without temporary change of time zone.
// Conversion from UTC date to second, signed 64-bit adjustable epoch version.
// Written by François Grieu, 2015-07-21; public domain.
#include <time.h> // needed for struct tm
#include <stdint.h> // needed for int_least64_t
#define MY_EPOCH 1970 // epoch year, changeable
typedef int_least64_t my_time_t; // type for seconds since MY_EPOCH
// my_mktime converts from struct tm UTC to non-leap seconds since
// 00:00:00 on the first UTC day of year MY_EPOCH (adjustable).
// It works since 1582 (start of Gregorian calendar), assuming an
// apocryphal extension of Coordinated Universal Time, until some
// event (like celestial impact) deeply messes with Earth.
// It strive to be strictly C99-conformant.
//
// input: Pointer to a struct tm with field tm_year, tm_mon, tm_mday,
// tm_hour, tm_min, tm_sec set per mktime convention; thus
// - tm_year is year minus 1900;
// - tm_mon is [0..11] for January to December, but [-2..14]
// works for November of previous year to February of next year;
// - tm_mday, tm_hour, tm_min, tm_sec similarly can be offset to
// the full range [-32767 to 32767].
// output: Number of non-leap seconds since beginning of the first UTC
// day of year MY_EPOCH, as a signed at-least-64-bit integer.
// The input is not changed (in particular, fields tm_wday,
// tm_yday, and tm_isdst are unchanged and ignored).
my_time_t my_mktime(const struct tm * ptm) {
int m, y = ptm->tm_year+2000;
if ((m = ptm->tm_mon)<2) { m += 12; --y; }
// compute number of days within constant, assuming appropriate origin
#define MY_MKTIME(Y,M,D) ((my_time_t)Y*365+Y/4-Y/100*3/4+(M+2)*153/5+D)
return ((( MY_MKTIME( y , m, ptm->tm_mday)
-MY_MKTIME((MY_EPOCH+99), 12, 1 )
)*24+ptm->tm_hour)*60+ptm->tm_min)*60+ptm->tm_sec;
#undef MY_MKTIME // this macro is private
}
Key observations allowing great simplification compared to the code in this and that answers:
numbering months from March, all months except the one before that origin repeat with a cycle of 5 months totaling 153 days alternating 31 and 30 days, so that, for any month, and without consideration for leap years, the number of days since the previous February can be computed (within a constant) using addition of an appropriate constant, multiplication by 153 and integer division by 5;
the correction in days accounting for the rule for leap year on years multiple-of-100 (which by exception to the multiple-of-4 rules are non-leap except if multiple of 400) can be computed (within a constant) by addition of an appropriate constant, integer division by 100, multiplication by 3, and integer division by 4;
we can compute correction for any epoch using the same formula we use in the main computation, and can do this with a macro so that this correction is computed at compilation time.
Here is another version not requiring 64-bit support, locked to 1970 origin.
// Conversion from UTC date to second, unsigned 32-bit Unix epoch version.
// Written by François Grieu, 2015-07-21; public domain.
#include <time.h> // needed for struct tm
#include <limits.h> // needed for UINT_MAX
#if UINT_MAX>=0xFFFFFFFF // unsigned is at least 32-bit
typedef unsigned my_time_t; // type for seconds since 1970
#else
typedef unsigned long my_time_t; // type for seconds since 1970
#endif
// my_mktime converts from struct tm UTC to non-leap seconds since
// 00:00:00 on the first UTC day of year 1970 (fixed).
// It works from 1970 to 2105 inclusive. It strives to be compatible
// with C compilers supporting // comments and claiming C89 conformance.
//
// input: Pointer to a struct tm with field tm_year, tm_mon, tm_mday,
// tm_hour, tm_min, tm_sec set per mktime convention; thus
// - tm_year is year minus 1900
// - tm_mon is [0..11] for January to December, but [-2..14]
// works for November of previous year to February of next year
// - tm_mday, tm_hour, tm_min, tm_sec similarly can be offset to
// the full range [-32767 to 32768], as long as the combination
// with tm_year gives a result within years [1970..2105], and
// tm_year>0.
// output: Number of non-leap seconds since beginning of the first UTC
// day of year 1970, as an unsigned at-least-32-bit integer.
// The input is not changed (in particular, fields tm_wday,
// tm_yday, and tm_isdst are unchanged and ignored).
my_time_t my_mktime(const struct tm * ptm) {
int m, y = ptm->tm_year;
if ((m = ptm->tm_mon)<2) { m += 12; --y; }
return ((( (my_time_t)(y-69)*365u+y/4-y/100*3/4+(m+2)*153/5-446+
ptm->tm_mday)*24u+ptm->tm_hour)*60u+ptm->tm_min)*60u+ptm->tm_sec;
}
A solution with little coding and portable, as it only uses mktime:
The parsed time has to be in struct tm tm.
if you use c++11, you might want to use std::get_time for parsing. It parses most time strings!
Before calling mktime() be sure tm.tm_isdst is set to zero, then mktime does not adjust for daylight savings,
// find the time_t of epoch, it is 0 on UTC, but timezone elsewhere
// If you newer change timezone while program is running, you only need to do this once
// if your compiler(VS2013) rejects line below, zero out tm yourself (use memset or "=0" on all members)
struct std::tm epoch = {};
epoch.tm_mday = 2; // to workaround new handling in VC, add a day
epoch.tm_year = 70;
time_t offset = mktime(&epoch) - 60*60*24; // and subtract it again
// Now we are ready to convert tm to time_t in UTC.
// as mktime adds timezone, subtracting offset(=timezone) gives us the right result
result = mktime(&tm)-offset
Edit based on comment from #Tom
As other answers note, mktime() (infuriatingly) assumes the tm struct is in the local timezone (even on platforms where tm has a tm_gmtoff field), and there is no standard, cross platform way to interpret your tm as GMT.
The following, though, is reasonably cross platform—it works on macOS, Windows (at least under MSVC), Linux, iOS, and Android.
tm some_time{};
... // Fill my_time
const time_t utc_timestamp =
#if defined(_WIN32)
_mkgmtime(&some_time)
#else // Assume POSIX
timegm(&some_time)
#endif
;
The tm structure used by mktime has a timezone field.
What happens if you put 'UTC' into the timzone field?
http://www.delorie.com/gnu/docs/glibc/libc_435.html
I've just been trying to figure out how to do this. I'm not convinced this solution is perfect (it depends on how accurately the runtime library calculates Daylight Savings), but it's working pretty well for my problem.
Initially I thought I could just calculate the difference between gmtime and localtime, and add that on to my converted timestamp, but that doesn't work because the difference will change according to the time of year that the code is run, and if your source time is in the other half of the year you'll be out by an hour.
So, the trick is to get the runtime library to calculate the difference between UTC and local time for the time you're trying to convert.
So what I'm doing is calculating my input time and then modifying that calculated time by plugging it back into localtime and gmtime and adding the difference of those two functions:
std::tm tm;
// Fill out tm with your input time.
std::time_t basetime = std::mktime( &tm );
std::time_t diff;
tm = *std::localtime( &basetime );
tm.tm_isdst = -1;
diff = std::mktime( &tm );
tm = *std::gmtime( &basetime );
tm.tm_isdst = -1;
diff -= std::mktime( &tm );
std::time_t finaltime = basetime + diff;
It's a bit of a roundabout way to calculate this, but I couldn't find any other way without resorting to helper libraries or writing my own conversion function.
The easy platform-independent way to convert UTC time from string to a timestamp is to use your own timegm.
Using mktime and manipulating timezone environment variables depends on correctly installed and configured TZ database. In one case some timezone links were incorrectly configured (likely side effect of trying different time server packages) which caused mktime-based algorithm to fail on that machine depending on the selected timezone and the time.
Trying to solve this problem with mktime without changing timezone is a dead end because string time (treated as local time) cannot be correctly resolved around the time when your local clock is set back one hour to turn off DST - the same string will match two points in time.
// Algorithm: http://howardhinnant.github.io/date_algorithms.html
inline int days_from_civil(int y, int m, int d) noexcept
{
y -= m <= 2;
int era = y / 400;
int yoe = y - era * 400; // [0, 399]
int doy = (153 * (m + (m > 2 ? -3 : 9)) + 2) / 5 + d - 1; // [0, 365]
int doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; // [0, 146096]
return era * 146097 + doe - 719468;
}
// Converts a broken-down time structure with UTC time to a simple time representation.
// It does not modify broken-down time structure as BSD timegm() does.
time_t timegm_const(std::tm const* t)
{
int year = t->tm_year + 1900;
int month = t->tm_mon; // 0-11
if (month > 11)
{
year += month / 12;
month %= 12;
}
else if (month < 0)
{
int years_diff = (11 - month) / 12;
year -= years_diff;
month += 12 * years_diff;
}
int days_since_epoch = days_from_civil(year, month + 1, t->tm_mday);
return 60 * (60 * (24L * days_since_1970 + t->tm_hour) + t->tm_min) + t->tm_sec;
}
This solution is free from external dependencies, threadsafe, portable and fast. Let me know if you can find any issues with the code.