I have a string with the following format:
2010-11-04T23:23:01Z
The Z indicates that the time is UTC.
I would rather store this as a epoch time to make comparison easy.
What is the recomended method for doing this?
Currently (after a quck search) the simplist algorithm is:
1: <Convert string to struct_tm: by manually parsing string>
2: Use mktime() to convert struct_tm to epoch time.
// Problem here is that mktime uses local time not UTC time.
You could utilize the
boost::date_time
and write a small manual parser (probably regexp-based) for your strings.X/Open provides a global
timezone
variable which indicates the number of seconds that local time is behind UTC. You can use this to adjust the output ofmktime()
:Linux provides
timegm
which is what you want (i.e. mktime for UTC time).Here is my solution, which I forced to only accept "Zulu" (Z timezone). Note that
strptime
doesn't actually seem to parse the time zone correctly, even though glib seems to have some support for that. That is why I just throw an exception if the string doesn't end in 'Z'.How about just computing the time difference between UTC and local time, then adding it to the value returned by
mktime
?New answer to an old question. Rationale for new answer: In case you want to use
<chrono>
types to solve a problem like this.In addition to C++11/C++14, you'll need this free, open source date/time library:
This program outputs:
If the parse fails in any way, an exception will be thrown. If you would rather not throw exceptions, don't
is.exceptions(std::ios::failbit);
, but instead check foris.fail()
.It's not an exact dup but you will find @Cubbi's answer from here useful, I wager. This specifically assumes UTC input.
Boost also support direct conversion from ISO 8601 via
boost::posix_time::from_iso_string
which callsboost::date_time::parse_iso_time
, here again you would just strip the trailing 'Z' and treat the TZ as implicit UTC.