How to make boost::log::keywords::file_name use UTC time? - c++

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(), .....

Related

Current UTC date string with to_iso_extended_string in millisecond format

I want to generate the current UTC date time in milliseconds precision but I am only be able to get it in seconds or microsec precision.
Is it possible to get it in milliseconds precision?
std::cout << to_iso_extended_string(microsec_clock::universal_time()) + "Z" << std::endl;
"2020-02-27T13:05:46.543801Z"
std::cout << to_iso_extended_string(second_clock::universal_time()) + "Z" << std::endl;
"2020-02-27T13:11:00Z"
Expected format:
"2020-02-27T13:05:46.543Z"
I think you can take a substring from the microsecond version.
Something like:
std::string microsec_time = to_iso_extended_string(microsec_clock::universal_time());
std::string millisec_time = microsec_time.substr(0, microsec_time.size()-3);
std::cout << millisec_time << 'Z' << std::endl;
It should give you the output you expect.

C++ std::localtime daylight saving time rule (dst) european vs american

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));

Cross-platform C++: convert to/from UTC/local time WITH historical tzdata

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

gmtime is giving me some times localtime?

I'm printing events in a multi-thread environment the console is a static mutex shared by all the threads.
The problem is randomly every hundred or thousand events the time I get is local time and not UTC.
I have seen this error just in Linux machines (build with g++) but not in Windows (build VC++). I have no clue where I could start, any idea?
void Publish(std::string source, std::string topic, std::string msg) NOEXCEPT {
console.lock();
std::time_t now = std::chrono::high_resolution_clock::to_time_t(*localTime);
char buf[50];
strftime(buf, sizeof (buf), "%Y-%m-%dT%H:%M:%S+00:00", gmtime(&now));
cout << buf << " " << source << " " << topic << " " << msg << endl;
cout.flush();
console.unlock();
}
struct tm * gmtime (const time_t * timer);
Converts time_t to tm as UTC time. This call uses the value pointed by timer to fill a tm structure with the values that represent the corresponding time, expressed as a UTC time (i.e., the time at the GMT timezone).
This must be working correctly.
However, not sure about this:
std::time_t now = std::chrono::high_resolution_clock::to_time_t(*localTime);
Is your *localtime giving the current time accurately under multithreaded situation? Is it a shared variable?
Instead could you use the following:
std::time_t now = time(0);

Boost Date Time Parsing string

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.