I am working on c++ real time application which is doing lot of date manipulations. For performance reasons, I made the UTC offset as configurable value which is read only once at the time of application initialization. But it is causing issues in DST zones.
When DST Changes happens, My UTC offset variable contain wrong value.
Calculating the Offset every time is not a optimal solution for me.
So is there anyway to notify my application about DST changes? So I can calculate the offset only when it need to modified.
Using the draft C++20 <chrono> facilities you can discover the std::chrono::system_clock::time_point for the next UTC offset change for any time zone, and then std::this_thread::sleep_until that time_point. When you wake, do whatever it is you want to do, such as compute a new UTC offset.
The new draft C++20 <chrono> library has been prototyped and is available as a free, open-source library under namespace date. This library is portable across VS, gcc and clang, and operates with C++11 and later.
Here is a sketch of how this might be coded:
#include "date/tz.h"
#include <thread>
template <class F>
void
on_utc_offset_change(date::time_zone const* tz, F f)
{
using namespace date;
using namespace std;
using namespace std::chrono;
while (true)
{
auto info = tz->get_info(system_clock::now());
f(info);
this_thread::sleep_until(info.end);
}
}
A time_zone has a get_info(system_clock::time_point) member function that returns a sys_info. The sys_info contains all information about a time_zone for a particular point in time:
struct sys_info
{
sys_seconds begin;
sys_seconds end;
std::chrono::seconds offset;
std::chrono::minutes save;
std::string abbrev;
};
The begin and end members are seconds-precision system_clock time_points that delineate the range [begin, end) for which this time_zone has this UTC offset and abbreviation (abbrev).
This function might be called like this:
auto lambda = [](date::sys_info const& info)
{
using namespace date;
std::cerr << "Current UTC offset: " << info.offset << '\n';
std::cerr << "Current tz abbreviation: " << info.abbrev << '\n';
std::cerr << "Sleeping until " << info.end << " UTC\n";
};
std::thread{on_utc_offset_change<decltype(lambda)>,
date::current_zone(),
lambda}.detach();
This detaches a thread that runs forever and every time the UTC offset changes for the computer's current time_zone (at the time the thread was launched), it prints out current information, for example.
Current UTC offset: -14400s
Current tz abbreviation: EDT
Sleeping until 2018-11-04 06:00:00 UTC
Alternatively you could run this for a specific time_zone which is not the computer's currently set time_zone with:
std::thread{on_utc_offset_change<decltype(lambda)>,
date::locate_zone("America/New_York"),
lambda}.detach();
Related
case
I need to write a program that moves files around at times that are set in a configuration file. The time can be 00:00:01 seconds untill 24:00:00 hours. This is converted into seconds. So if somebody wants to move a file at 12:00:00 pm today, the move time is 12 * 60 * 60 = 43200 seconds. This is done every day and the program needs to check if that time is reached.
I use the chrono library to get the time now since epoch in seconds using:
auto dayInSeconds = 86400;
auto currentTime = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock().now().time_since_epoch());
auto timeWithoutDays = currentTime % dayInSeconds;
std::cout << "time in seconds today: " << timeWithoutDays.count() << std::endl;
problem
This shows me the current time since epoch in seconds. But now for example ( 13:45 Amsterdam time) it returns a number of: 42294. If I run it exactly five seconds later in a loop it returns 42299. So the counting seems to be correct. What is not correct, is that 42299 seconds is 1174 hours (42299/ 60 /60). Which should mean that is now 11:somewhat AM but its 13:32 PM. Or not? What am I doing wrong? I just need to know, how many seconds have passed since 00:00:00 this day. So i can check if the user set time is passed and stuff needs to be done.
I would like to keep using the chrono library for all sorts of reasons, but mainly because I understand that one. So if answers use that library, it would be a great help. I have a feeling i'm doing something completely stupid.
fix
For any other that seeks the same answer. I fixed it like this, it seems to work:
auto dayInSeconds = 86400;
auto amsterdamUTCPlusTime = 7200;
auto currentTime = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock().now().time_since_epoch());
auto timeWithoutDays = currentTime % dayInSeconds;
auto currentTimeInSeconds = timeWithoutDays.count() + amsterdamUTCPlusTime;
std::cout << "time in seconds today: " << currentTimeInSeconds << std::endl;
C++20 brings extensions to <chrono> to deal with timezones. It isn't shipping yet (to the best of my knowledge). But here is what it will look like:
#include <chrono>
#include <iostream>
int
main()
{
using namespace std;
using namespace std::chrono;
zoned_time zt{"Europe/Amsterdam", floor<seconds>(system_clock::now())};
auto lt = zt.get_local_time();
auto tod = lt - floor<days>(lt);
cout << "time in seconds today: " << tod.count() << '\n';
cout << hh_mm_ss{tod} << '\n';
}
Example output:
time in seconds today: 71923
19:58:43
If your computer's local time zone setting is already set to "Europe/Amsterdam", then "Europe/Amsterdam" above can be replaced with current_zone().
This gets the current time in UTC, truncates it to seconds precision, and then pairs it with the "Europe/Amsterdam" time_zone to create a zoned_time. Then the local time is extracted from the zoned_time. The local time of day is simply the local time minus the beginning of that day (floor<days>(lt)). This is stored in tod which has type seconds. Wrapping it in a hh_mm_ss prints it out in a hh:mm:ss format.
There exists a free, open-source C++20 <chrono> preview library which can be used with C++11/14/17 to do this. To use it, it must be installed. There's a single source file to be compiled, tz.cpp, and it needs to have access to the IANA time zone database, which can be automatically downloaded with specific build settings.
The source code above must be trivially modified by adding #include "date/tz.h" and using namespace date;. In C++11 and 14, change zoned_time to zoned_seconds, and hh_mm_ss to hh_mm_ss<seconds>.
Another possibility is to build your own UTC offset calculator for just Amsterdam (assuming current rules). The advantage of this is that it can use of subset of the free, open-source C++20 <chrono> preview library which is header-only, and thus requires no installation, and does not need the IANA time zone database. That could like this:
#include "date/date.h"
#include <chrono>
#include <iostream>
int
main()
{
using namespace date;
using namespace std;
using namespace std::chrono;
auto AmsterdamOffset = [](system_clock::time_point tp)
{
auto const y = year_month_day{floor<days>(tp)}.year();
auto const start = sys_days{Sunday[last]/March/y} + 1h;
auto const end = sys_days{Sunday[last]/October/y} + 1h;
if (start <= tp && tp < end)
return 2h;
return 1h;
};
auto now = floor<seconds>(system_clock::now());
auto local_now = now + AmsterdamOffset(now);
auto tod = local_now - floor<days>(local_now);
cout << "time in seconds today: " << tod.count() << '\n';
cout << hh_mm_ss{tod} << '\n';
}
This program hardcodes the fact that Amsterdam daylight saving begins on the last Sunday of March at 01:00:00 UTC and ends on the last Sunday of October at 01:00:00 UTC.
After that, the program logic is much like the C++20 solution shown above. In C++11, 1h and 2h will have to be changed to hours{1} and hours{2} respectively.
And yet another approach: Posix time zones
There is also a Posix time zone library at this link in ptz.h. This is also a header-only library, so no install issues. It allows you to use the C++20 zoned_time combined with Posix time zones. This will give you the same results as the example above with the "hard coded" rules for Amsterdam (which are valid back through 1978).
#include "date/ptz.h"
#include <chrono>
#include <iostream>
int
main()
{
using namespace date;
using namespace std;
using namespace std::chrono;
// Amsterdam rules
Posix::time_zone tz{"CET-1CEST,M3.5.0,M10.5.0/3"};
zoned_time zt{tz, floor<seconds>(system_clock::now())};
auto lt = zt.get_local_time();
auto tod = lt - floor<days>(lt);
cout << "time in seconds today: " << tod.count() << '\n';
cout << hh_mm_ss{tod} << '\n';
}
The above assumes C++17. If in C++11 or 14 the syntax becomes a little messier:
zoned_time<seconds, Posix::time_zone> zt{tz, floor<seconds>(system_clock::now())};
The Posix::time_zone is not part of the C++20 <chrono> library, but is compatible with it. It can be used with the C++20 std::chrono::zoned_time class template as shown above.
You can use localtime function and get the current time from system.
int getIntTime()
{
struct timeb now;
struct tm *curtime;
curtime = localtime(&now);
return(curtime->tm_hour * 10000L + curtime->tm_min * 100L + curtime->tm_sec);
}
And also you should convert the set time in confgi file to same as output of this function and compare them as follow:
if(getIntTime() >= converted_time_configfile )
{
//do processing
}
I've a a problem with time numbers,
Lets supose that i've this time: 05-03-2016 09:45:55.064371, I've a function that converts this to miliseconds (Using Epoch (reference_date), using ctime and chrono libraries)->1457167555064, now what I want to find is the full minute with miliseconds before and after this time, so in this case what I want is to find 05-03-2016 09:45:00.000000 and 05-03-2016 09:46:00.000000
I'm open to lisent another way to find if a date is inside a minute.
Thank you!
The most convenient tool for this is the new std::chrono::floor and std::chrono::ceil in C++17. If you don't have C++17, you can get a preview of these in Howard Hinnant's free, open-source datetime library:
#include "date/date.h"
#include <iostream>
int
main()
{
using namespace date;
using namespace std::chrono;
sys_time<milliseconds> tp{1457167555064ms};
sys_time<milliseconds> t0 = floor<minutes>(tp);
sys_time<milliseconds> t1 = ceil<minutes>(tp);
std::cout << t0 << '\n';
std::cout << tp << '\n';
std::cout << t1 << '\n';
}
Output:
2016-03-05 08:45:00.000
2016-03-05 08:45:55.064
2016-03-05 08:46:00.000
These times are all UTC. You appear to have a local time at UTC +01:00. There is also a timezone library at this same GitHub site that you can use to convert between UTC and local time, or between any two IANA timezones.
Above, sys_time<milliseconds> is simply a type alias for time_point<system_clock, milliseconds>.
I have a time_t that represents the time in seconds since epoch. Those seconds refer to the local time.
I want to convert them to UTC.
Is there a way to do this in C++?
I'm going to show two ways of doing this:
Using the C API.
Using a modern C++11/14 library based on top of <chrono>.
For the purposes of this demo, I'm assuming that the current number of seconds in the local time zone is 1,470,003,841. My local time zone is America/New_York, and so the results I get reflect that we are currently at -0400 UTC.
First the C API:
This API is not type-safe and is very error prone. I made several mistakes just while coding up this answer, but I was able to quickly detect these mistakes because I was checking the answers against the 2nd technique.
#include <ctime>
#include <iostream>
int
main()
{
std::time_t lt = 1470003841;
auto local_field = *std::gmtime(<);
local_field.tm_isdst = -1;
auto utc = std::mktime(&local_field);
std::cout << utc << '\n'; // 1470018241
char buf[30];
std::strftime(buf, sizeof(buf), "%F %T %Z\n", &local_field);
std::cout << buf;
auto utc_field = *std::gmtime(&utc);
std::strftime(buf, sizeof(buf), "%F %T UTC\n", &utc_field);
std::cout << buf;
}
First I initialize the time_t. Now there is no C API to go from a local time_t to a UTC time_t. However you can use gmtime to go from a UTC time_t to a UTC tm (from serial to field type, all in UTC). So the first step is to lie to gmtime, telling it you've got a UTC time_t. And then when you get the result back you just pretend you've got a local tm instead of a UTC tm. Clear so far? This is:
auto local_field = *std::gmtime(<);
Now before you go (and I personally messed this part up the first time through) you have to augment this field type to say that you don't know if it is currently daylight saving or not. This causes subsequent steps to figure that out for you:
local_field.tm_isdst = -1;
Next you can use make_time to convert a local tm to a UTC time_t:
auto utc = std::mktime(&local_field);
You can print that out, and for me it is:
1470018241
which is 4h greater. The rest of the function is to print out these times in human readable format so that you can debug this stuff. For me it output:
2016-07-31 22:24:01 EDT
2016-08-01 02:24:01 UTC
A modern C++ API:
There exist no facilities in the std::lib to do this. However you can use this free, open source (MIT license) library for this.
#include "date/tz.h"
#include <iostream>
int
main()
{
using namespace date;
using namespace std::chrono_literals;
auto zt = make_zoned(current_zone(), local_seconds{1470003841s});
std::cout << zt.get_sys_time().time_since_epoch() << '\n'; // 1470018241s
std::cout << zt << '\n';
std::cout << zt.get_sys_time() << " UTC\n";
}
The first step is to create the local time in terms of seconds since the epoch:
local_seconds{1470003841s}
The next thing to do is to create a zoned_time which is a pairing of this local time and the current time zone:
auto zt = make_zoned(current_zone(), local_seconds(1470003841s));
Then you can simply print out the UTC number of seconds of this pairing:
std::cout << zt.get_sys_time().time_since_epoch() << '\n';
This output for me:
1470018241s
(4h later than the input). To print out this result as I did in the C API:
std::cout << zt << '\n';
std::cout << zt.get_sys_time() << " UTC\n";
which outputs:
2016-07-31 22:24:01 EDT
2016-08-01 02:24:01 UTC
In this modern C++ approach, the local time and the UTC time are different types, making it much more likely that I catch accidental mixing of these two concepts at compile time (as opposed to creating run time errors).
Update for C++20
The second technique will be available in C++20 with the following syntax:
#include <chrono>
#include <iostream>
int
main()
{
using namespace std::chrono;
zoned_time zt{current_zone(), local_seconds{1470003841s}};
std::cout << zt.get_sys_time().time_since_epoch() << '\n'; // 1470018241s
std::cout << zt << '\n';
std::cout << zt.get_sys_time() << " UTC\n";
}
You can use gmtime:
Convert time_t to tm as UTC time 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).
(c) http://www.cplusplus.com/reference/ctime/gmtime/
If you are okay with using Abseil's time library, one other way to do this is:
auto civil_second =
absl::LocalTimeZone().At(absl::FromTimeT(<your time_t>)).cs;
time_t time_in_utc = absl::ToTimeT(absl::FromCivil(civil_second, absl::UTCTimeZone()));
(Maybe there is a simpler set of calls in the library to do this, but I have not explored further. :))
Normaly, you would convert from time_t to struct tm and there aren't many examples of converting from time_t to time_t in a different time zone (UTC in case of the OP's question). I wrote these 2 functions for that exact purpose. They may be useful when you are only in a need ot using time_t but in a specific time zone.
time_t TimeAsGMT(time_t t)
{
std::chrono::zoned_time zt{"UTC", std::chrono::system_clock::from_time_t(t)};
return std::chrono::system_clock::to_time_t(zt.get_sys_time());
}
or if you want the current time as UTC in the form of time_t
time_t CurTimeAsGMT()
{
std::chrono::zoned_time zt{"UTC", std::chrono::system_clock::now()}; // Get the time in UTC time zone
return std::chrono::system_clock::to_time_t(zt.get_sys_time()); // return this time as time_t
}
If you run both functions and compare the initial value and the result value, you will see that the difference matches the difference between your current time (at your current time zone) and UTC / GMT time zone.
Hello I'm trying to get time elapsed since epoch using boost in UTC but it seems that microsec_clock::universal_time(); doesn't return UTC time, instead it returns time in timezone of PC.
How can I get current time in miliseconds in UTC using boost?
Here is my code that I'm using
const long long unix_timestmap_now()
{
ptime time_t_epoch(date(1970, 1, 1));
ptime now = microsec_clock::universal_time();
time_duration diff = now - time_t_epoch;
return diff.total_milliseconds();;
}
Why you use a boost? All needed (which refers to the time) moved to the STL in C ++ .
It is important - not everyone knows that "unix timestamp" at a time is the same for the whole world, ie if the check time on the server in Russia, and for example on a server in the USA, the value will be the same (of course under the condition that both servers correct time right), it differs only in its transformation into understandable for people of form, depending on the server settings. And of course the reverse priobrazovanie will also vary if you do not set the time zone.
Tested on cpp.sh
#include <iostream>
#include <chrono>
int main ()
{
using namespace std::chrono;
system_clock::time_point tp = system_clock::now();
system_clock::duration dtn = tp.time_since_epoch();
std::cout << "current time since epoch, expressed in:" << std::endl;
std::cout << "milliseconds: " << duration_cast<milliseconds>(dtn).count();
std::cout << std::endl;
return 0;
}
How do I get the current UTC offset (as in time zone, but just the UTC offset of the current moment)?
I need an answer like "+02:00".
There are two parts to this question:
Get the UTC offset as a boost::posix_time::time_duration
Format the time_duration as specified
Apparently, getting the local time zone is not exposed very well in a widely implemented API. We can, however, get it by taking the difference of a moment relative to UTC and the same moment relative to the current time zone, like this:
boost::posix_time::time_duration get_utc_offset() {
using namespace boost::posix_time;
// boost::date_time::c_local_adjustor uses the C-API to adjust a
// moment given in utc to the same moment in the local time zone.
typedef boost::date_time::c_local_adjustor<ptime> local_adj;
const ptime utc_now = second_clock::universal_time();
const ptime now = local_adj::utc_to_local(utc_now);
return now - utc_now;
}
Formatting the offset as specified is just a matter of imbuing the right time_facet:
std::string get_utc_offset_string() {
std::stringstream out;
using namespace boost::posix_time;
time_facet* tf = new time_facet();
tf->time_duration_format("%+%H:%M");
out.imbue(std::locale(out.getloc(), tf));
out << get_utc_offset();
return out.str();
}
Now, get_utc_offset_string() will yield the desired result.
Since C++11 you can use chrono and std::put_time:
#include <chrono>
#include <iomanip>
#include <iostream>
int main ()
{
using sc = std::chrono::system_clock;
auto tm = sc::to_time_t(sc::now());
std::cout << std::put_time(std::localtime(&tm), "formatted time: %Y-%m-%dT%X%z\n");
std::cout << "just the offset: " << std::put_time(std::localtime(&tm), "%z\n");
}
This produces the following output:
formatted time: 2018-02-15T10:25:27+0100
just the offset: +0100