I have looked at many examples seem to address this simple case. The string I want to parse is:
"2012-06-01 16:45:34 EDT"
I have tried to create a local_time_input_facet with the folloiwng:
"%Y-%m-%d %H:%M:%S %Z"
The zone pointer of the local_date_time object is always not set. Reading the documentation is confusing:
%Z *!
Full time zone name (output only). This flag is ignored when using the time_facet with a ptime.
"EDT" // Eastern Daylight Time
Has anyone done this before?
UPDATE: I have updated the code to illustrate the problem a little better:
using namespace std;
using namespace boost::local_time;
int main()
{
stringstream ss;
// Set up the input datetime format.
local_time_input_facet *input_facet
= new local_time_input_facet("%Y-%m-%d %H:%M:%S %ZP");
ss.imbue(std::locale(ss.getloc(), input_facet));
local_date_time ldt(not_a_date_time),ldt1(not_a_date_time);
// Read a time into ldt
ss.str("2012-06-01 17:45:34 EDT");
ss >> ldt;
ss.str("2012-06-01 17:45:34 CDT");
ss >> ldt1;
std::cerr << (ldt - ldt1).total_seconds() << std::endl;
// Write the time to stdout.
cout << "Full Time:\t" << ldt.to_string() << endl;
cout << "Local time:\t" << ldt.local_time() << endl;
cout << "Time zone:\t" << ldt.zone_as_posix_string() << endl;
cout << "Zone abbrev:\t" << ldt.zone_abbrev() << endl;
cout << "Zone offset:\t" << ldt.zone_abbrev(true) << endl;
cout << "Full Time:\t" << ldt1.to_string() << endl;
cout << "Local time:\t" << ldt1.local_time() << endl;
cout << "Time zone:\t" << ldt1.zone_as_posix_string() << endl;
cout << "Zone abbrev:\t" << ldt1.zone_abbrev() << endl;
cout << "Zone offset:\t" << ldt1.zone_abbrev(true) << endl;
return 0;
}
OUTPUT:
0
Full Time: 2012-Jun-01 17:45:34 EDT
Local time: 2012-Jun-01 17:45:34
Time zone: EDT+00
Zone abbrev: EDT
Zone offset: +0000
Full Time: 2012-Jun-01 17:45:34 CDT
Local time: 2012-Jun-01 17:45:34
Time zone: CDT+00
Zone abbrev: CDT
Zone offset: +0000
The Bug
According to boost's documentation here: http://www.boost.org/doc/libs/1_57_0/doc/html/date_time/date_time_io.html#date_time.format_flags
%Z is:
Full time zone name (output only).
It also says to %ZP:
Posix time zone string (available to both input and output).
So you need to change %Z to %ZP. Now your timestamps will parse. However, you'll notice that the zone offset will not be set.
Posix Time Zone Strings
For a Posix time zone string, you'll need to specify at least the zone abbreviation and the offset from UTC, e.g. EST-5.
A full Posix time zone string is formatted as:
"std offset dst [offset],start[/time],end[/time]"
with no spaces, according to http://www.boost.org/doc/libs/1_57_0/doc/html/date_time/local_time.html#date_time.local_time.posix_time_zone
Here are some examples of full Posix time zone strings for EST and PST:
EST-5EDT,M3.2.0,M11.1.0
PST-8PDT,M4.1.0,M10.1.0
This contains the information on when Daylight Savings Time is in effect.
However, you may be able to get away with EDT-4 in your case, depending on what you're doing with it.
It should be noted that as simple as Posix time zones are, they are limited in that they don't account for historical changes in time zone rules. I think it's best to just avoid working with time zones in the first place.
What if I can't control the input format?
As the OP noted in the comments, the offsets are not listed in his input timestamps. One solution is to read the zone abbreviation from the end of the input timestamp (e.g. "EDT"), and check it against a map of known zone abbreviations:
std::map<std::string, std::string> zone_map;
zone_map["EST"] = "EST-5EDT,M4.1.0,M10.5.0"; // Eastern Standard Time
zone_map["EDT"] = zone_map["EST"]; // Eastern Daylight Time
zone_map["PST"] = "PST-8PDT,M4.1.0,M10.1.0"; // Pacific Standard Time
zone_map["PDT"] = zone_map["PST"]; // Pacific Daylight Time
// ...
(Note the DST zones above should be the same as the standard time zones.)
You might also get away with with just storing simple UTC offsets:
zone_map["EST"] = "EST-5"; // Eastern Standard Time
zone_map["EDT"] = "EDT-4"; // Eastern Daylight Time
// ...
Working Example
Here's an example that uses a built-in timezone database:
#include <map>
#include <string>
#include <sstream>
#include <iostream>
#include <boost/date_time/local_time/local_time.hpp>
using namespace boost::local_time;
int main()
{
// A little database of time zones.
std::map<std::string, std::string> zone_map;
zone_map["EST"] = "EST-5EDT,M4.1.0,M10.5.0"; // Eastern Standard Time
zone_map["EDT"] = zone_map["EST"]; // Eastern Daylight Time
zone_map["PST"] = "PST-8PDT,M4.1.0,M10.1.0"; // Pacific Standard Time
zone_map["PDT"] = zone_map["PST"]; // Pacific Daylight Time
// ...
// This is our input timestamp.
std::string timestamp = "2012-06-01 16:45:34 EDT";
// Replace time zone abbrev with full Posix time zone.
const size_t abbrev_pos = timestamp.find_last_of(' ') + 1;
const std::string abbrev = timestamp.substr(abbrev_pos);
timestamp.replace(abbrev_pos, std::string::npos, zone_map[abbrev]);
std::cout << "Time stamp with full timezone: " << timestamp << std::endl;
// Set up the input datetime format.
local_time_input_facet *input_facet = new local_time_input_facet("%Y-%m-%d %H:%M:%S %ZP");
std::stringstream ss;
ss.imbue(std::locale(ss.getloc(), input_facet));
// This is our output date time.
local_date_time ldt(not_a_date_time);
// Read the timestamp into ldt.
ss.str(timestamp);
ss >> ldt;
// Write the time to stdout.
std::cout << "Full Time:\t" << ldt.to_string() << std::endl
<< "Local time:\t" << ldt.local_time() << std::endl
<< "Time zone:\t" << ldt.zone_as_posix_string() << std::endl
<< "Zone abbrev:\t" << ldt.zone_abbrev() << std::endl
<< "Zone offset:\t" << ldt.zone_abbrev(true) << std::endl;
return 0;
}
This outputs:
Time stamp with full timezone: 2012-06-01 16:45:34 EST-5EDT,M4.1.0,M10.5.0
Full Time: 2012-Jun-01 16:45:34 EDT
Local time: 2012-Jun-01 16:45:34
Time zone: EST-05EDT+01,M4.1.0/02:00,M10.5.0/02:00
Zone abbrev: EDT
Zone offset: -0400
While the solution here may not be ideal, it's the only way I can see of doing it.
Related
I have converted a timestamp (UTC) since Epoch to a boost::posix_time::ptime and applied a timezone, resulting in a boost::local_time::local_date_time object. However, I cannot retrieve the year, month, day, hh/mm/ss/ns or nanoseconds since midnight for the adjusted date time.
It appears the local_date_time object doesn't provide getters for these.
I can't get these from the boost::posix_time::ptime because it hasn't been shifted for timezone.
What's the best approach?
using namespace boost::gregorian;
using namespace boost::local_time;
using namespace boost::posix_time;
// Create timezone
tz_database tz_db;
tz_db.load_from_file("libs/date_time/data/date_time_zonespec.csv");
time_zone_ptr chicago_tz = tz_db.time_zone_from_region("America/Chicago");
// Create Epoch offset (seconds)
std::time_t btime_ = nanosSinceEpochUTC / 1E9;
ptime dateTime = boost::posix_time::from_time_t(btime_);
// Create local Chicago time at Epoch offset
const local_date_time chicago(dateTime, chicago_tz);
// I need to retrieve the year/month/day/hh/mm/ss etc from the adjusted time, not the ptime.
The time properties are in the time_of_day() sub object. The representation type of that subobject is time_duration and it has all the accessors you want:
Live On Coliru
#include <boost/date_time/local_time/local_time.hpp>
#include <boost/date_time/tz_db_base.hpp>
int main() {
// Create timezone
boost::local_time::tz_database tz_db;
{
std::istringstream iss(R"("America/Chicago","CST","Central Standard Time","CDT","Central Daylight Time","-06:00:00","+01:00:00","2;0;3","+02:00:00","1;0;11","+02:00:00")");
tz_db.load_from_stream(iss);
}
auto chicago_tz = tz_db.time_zone_from_region("America/Chicago");
// Create Epoch offset (seconds)
std::time_t btime_ = 1596241091; // nanosSinceEpochUTC / 1E9;
auto dateTime = boost::posix_time::from_time_t(btime_);
std::cout << "ptime: " << dateTime << "\n";
// Create local Chicago time at Epoch offset
const boost::local_time::local_date_time chicago(dateTime, chicago_tz);
std::cout << "local_date_time: " << chicago << "\n";
// I need to retrieve the year/month/day/hh/mm/ss etc from the adjusted
// time, not the ptime.
std::cout << "year/m/d: " << chicago.local_time().date() << "\n";
auto tod = chicago.local_time().time_of_day();
std::cout << "time_of_day: " << tod << "\n";
std::cout << "hh, mm, ss: " <<
tod.hours() << ", " <<
tod.minutes() << ", " <<
tod.seconds() << "\n";
}
As you can see, it's important to access through the local_time() accessor. Note how all the items (day, month, hours) wrapped back correctly according to the time zone.
Prints:
ptime: 2020-Aug-01 00:18:11
local_date_time: 2020-Jul-31 19:18:11 CDT
year/m/d: 2020-Jul-31
time_of_day: 19:18:11
hh, mm, ss: 19, 18, 11
What I do is as follows: I am naming one class after the name of a time zone. In my case gmt and fetch everything via instances of my very own time as well as date class.
class gmt {
string get(string& s) {
this->dt= this->d.getDay();
this->tm= this->d.getTime();
s= "expires="+this->d.getName(this->d.getDayName())
+", " +this->dt.substr( 0, 2) +"-" +this->d.getMonthName() +"-" +this->dt.substr( 8, 2)
+" " +this->tm +" GMT";
return s;
}
friend class cookie;
string dt, tm;
MyDate d;
};
Okay, it isn't "boost" but you can solve it via its own std and isn't that contrary.
I've problem with use of the std::localtime function. When I transform a std::time_t to a local struct tm, it always use the american daylight saving time whereas I want to use the european one (France).
UTC : 03/19/16 16:56 is transformed in Local : 03/19/16 18:56.
At this date, normally, local is 17:56 (UTC+1). The DST happens on the 27th in France.
After several tests, it seems that the used DST is based on the american rule : DST happens on second sunday in march.
I've also changed the TZ environement variable, but it also fails.
`
if( putenv( "TZ=CET-1CEST-2,M3.5.0/2,M10.5.0/3" ) != 0 ) {
std::cout << "Unable to set TZ" << std::endl;
} else {
tz = getenv("TZ");
if (tz) std::cout << tz << std::endl;
else std::cout << "TZ not defined" << std::endl; tzset();
}
struct std::tm t;
t.tm_sec = 0;
t.tm_min = 56;
t.tm_hour = 18;
t.tm_mday = 19;
t.tm_mon = 3-1;
t.tm_year = 2016-1900;
t.tm_isdst = -1;
std::time_t tt = std::mktime(&t);
std::cout << "UTC: " << std::put_time(std::gmtime(&tt), "%c %Z") << '\n'; // UTC : 03/19/16 16:56
std::cout << "local: " << std::put_time(std::localtime(&tt), "%c %Z") << '\n'; // Local : 03/19/16 18:56 (not waited result)
`
As a precision, I use the bcc32c compiler (the embarcadero C++ clang based computer).
I hope I'm clear enough and you'll be able to help me.
Thanks in advance
If you have C++11 (or later) available, which includes <chrono>, and if you are willing to work with the <chrono> system. And if you are willing to use this free, open-source timezone library. Then this is a very simple matter:
#include "tz.h"
#include <iostream>
int
main()
{
using namespace date;
using namespace std::chrono_literals;
auto zt = make_zoned("Europe/Paris", sys_days{2016_y/mar/19} + 18h + 56min);
std::cout << format("%m/%d/%y %H:%M %Z", zt.get_sys_time()) << '\n';
std::cout << format("%m/%d/%y %H:%M %Z", zt) << '\n';
}
Output:
03/19/16 18:56 UTC
03/19/16 19:56 CET
In short, you form one zoned_time by pairing a timezone of your choosing
("Europe/Paris"), with a sys_time (UTC). Then you can format that zoned_time both by extracting the sys_time back out of it, and by formatting the zoned_time itself, which will use the local_time of the zoned_time.
I attempted to use formatting that was consistent with your comments. You could of course you any format you want. You can also include any std::locale your system supports as the first argument in the calls to format (which %c would take advantage of).
You can also extract individual fields both from the sys_time and from the local_time if you need to, or do other date or time computations. This is more than just a formatting library.
If you are starting with a time_t, there is a static member function of std::chrono::system_clock to convert a time_t to a system_clock::time_point. You can then use that time_point in place of sys_days{2016_y/mar/19} + 18h + 56min in this example:
auto zt = make_zoned("Europe/Paris", system_clock::from_time_t(t));
When using boost::log I can use the following to make the file name use a time stamp as part of the name, but I would really like that time to be in UTC time not local time. How could this be achieved?
boost::log::add_file_log(
boost::log::keywords::file_name = "Log-%Y%m%d-%H00.log",
I already know how to make the timestamps within the file_name be UTC, but I haven't been able to figure out how to make the file_name UTC.
Thanks in Advance
Bruce
There is no way to use UTC timestamps in file names, unless you want to patch Boost.Log.
I would really like that time to be in UTC time not local time
UTC time is "within about 1 second, mean solar time at 0° longitude;" see Wikipedia.
CST (here in Texas) is (essentially) 6 hours different from UTC ... your local time may differ.
Google reports "Coordinated Universal Time is 6 hours ahead of Central Time ".
I think you can compute UTC from local time just by knowing the offset.
My attempt would be:
std::string filename;
{
std::stringstream ss;
ss << "Log-" << year << month << day
<< "-" << hour << "00.log";
filename = ss.str();
}
and I found this:
std::time_t t = std::time(nullptr);
std::cout << "UTC: " << std::put_time(std::gmtime(&t), "%c %Z");
std::cout << "local: " << std::put_time(std::localtime(&t), "%c %Z");
Combine the two? GoodLuck
You can do this (with local time)
std::time_t t = std::time(nullptr);
std::stringstream filename;
filename << "Log-" << std::put_time(std::localtime(&t), "%Y%m%d-%H00") << ".log";
boost::log::add_file_log(
boost::log::keywords::file_name = filename.str(), .....
I need to convert times from UTC to a timezone selected by the user. I also have to convert from user input in that time zone to store in UTC.
Currently timezones are defined in Olson format ("America/Los Angeles").
A solution was easy on Linux with timegm, but I can not find a cross platform solution (or any solution) that does the exact same thing on Windows.
I can not use Boost.Date_Time (http://www.boost.org/doc/libs/1_57_0/doc/html/date_time.html) because it does not support historical timezone changes such as varying DST periods over the years. Someone apparently submitted a patch years ago but it does not appear to have been accepted.
The only other solution that seems plausible is to use data and code from: https://www.iana.org/time-zones
Has anyone tried this, or do you have a better idea?
Here is a cross platform, open source C++11/C++14 timezone library that wraps the IANA timezone database, including all historical data. The IANA database is the currently maintained Olson database.
An example from this library is:
#include "tz.h"
#include <iostream>
int
main()
{
using namespace std::chrono_literals;
using namespace date;
auto departure = make_zoned("America/New_York",
local_days{dec/30/1978} + 12h + 1min);
auto flight_length = 14h + 44min;
auto arrival = make_zoned("Asia/Tehran",
departure.get_sys_time() + flight_length);
std::cout << "departure NYC time: " << departure << '\n';
std::cout << "flight time is " << make_time(flight_length) << '\n';
std::cout << "arrival Tehran time: " << arrival << '\n';
}
which outputs:
departure NYC time: 1978-12-30 12:01:00 EST
flight time is 14:44
arrival Tehran time: 1978-12-31 11:45:00 IRST
Note the date: December of 1978. This is historically accurate (as far as timezone handling is concerned). The paper goes on to demonstrate how the same flight on the next day has a different arrival time because of a timezone change in Tehran.
The example above does not handle leap seconds. However if you actually do want to handle leap seconds, the library can handle it with a small amount of extra work:
#include "tz.h"
#include <iostream>
int
main()
{
using namespace std::chrono_literals;
using namespace date;
auto departure = make_zoned("America/New_York",
local_days{dec/31/1978} + 12h + 1min);
auto departure_utc = to_utc_time(departure.get_sys_time());
auto flight_length = 14h + 44min;
auto arrival = make_zoned("Asia/Tehran",
to_sys_time(departure_utc + flight_length));
std::cout << "departure NYC time: " << departure << '\n';
std::cout << "flight time is " << make_time(flight_length) << '\n';
std::cout << "arrival Tehran time: " << arrival << '\n';
}
departure NYC time: 1978-12-31 12:01:00 EST
flight time is 14:44
arrival Tehran time: 1979-01-01 11:14:59 IRST
This is all described in detail at:
http://howardhinnant.github.io/date/tz.html
and freely available at:
https://github.com/HowardHinnant/date
Why RWTime is giving 1 hour more
#include <rw/rwtime.h>
#include <rw/rwdate.h>
#include <rw/rstream.h>
main(){
RWTime t; // Current time
RWTime d(RWTime::beginDST(1990, RWZone::local()));
cout << "Current time: " << RWDate(t) << " " << t <<
endl;
cout << "Start of DST, 1990: " << RWDate(d) << " " << d <<
endl;
}
Above program prints:
root#otp42mas:/home/nmsadm/sapna/cProgS# ./a.out
Current time: 10/27/10 10/27/10 17:08:06
Start of DST, 1990: 04/01/90 04/01/90 03:00:00
But date gives:
root#otp42mas:/home/nmsadm/sapna/cProgS# date
Wed Oct 27 16:08:10 IST 2010
My sixth sense is tingling, it tells me that the answer has something to do with the daylight savings time ... I'm not sure why, though ...
By default RWZone::local() will return an RWZone implementation based on North American DST transitions. RWZone::os() provides an RWZone implementation based DST transitions derived from the current system time zone. RWZone::local() can be updated to use RWZone::os() using:
RWZone::local(&RWZone::os());