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
}
Related
I'm trying to find the best way to see if the current time is before a specified time. Say I want to see if it's before 14:32. What's the best way to do this in C++? Ideally I'd be able to build some time object that represents 14:32, then compare it with the current time as some object.
This is what I'm doing right now. Pretty messy and uses 3 different representations of time.
int hour_ = 14;
int min_ = 32;
std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
std::time_t tt = std::chrono::system_clock::to_time_t(now);
std::tm utc_tm = *gmtime(&tt);
if ((utc_tm.tm_hour < hour_) || (utc_tm.tm_hour == hour_ && utc_tm.tm_min < min_) ) {
std::cout << "It's before " << hour_ << ":" << min_ << std::endl;
}
Here is how you can do it in C++20. Later I will show how to convert this to use a free, open-source C++20 chrono preview library which works with C++11/14/17.
#include <chrono>
bool
is_now_before(std::chrono::minutes local_config_tod)
{
using namespace std::chrono;
auto tz = current_zone();
auto now = system_clock::now();
auto local_day = floor<days>(zoned_time{tz, now}.get_local_time());
auto utc_config = zoned_time{tz, local_day + local_config_tod}.get_sys_time();
return now < utc_config;
}
The parameter has type minutes which will be interpreted to be the local time of day in minutes. For example 14:32 is represented by minutes{872}. This representation is compact (one integer), and it is trivial to convert {hours, minutes} to just minutes (shown below).
current_zone() gets the computer's current local time zone. This information is needed twice in this function, so it is best to just get it once. Not only does this save the result, but it also sidesteps the problem of the local time zone changing out from under you (between multiple calls) in a mobile device.
Next the current time is obtained (just once) via system_clock. This gives the current time in UTC.
Now we have a choice:
We could do the comparison in UTC, or
We could do the comparison in local time.
Doing the comparison in UTC is less error prone in the corner case that the UTC offset is changing in the current local day (such as going on or off of daylight saving).
To convert the local config time-of-day (local_config_tod) to a UTC time_point one first has to find out what the current local day is. In general this can be different than the current UTC day. So the current UTC now has to be converted to local time, and then truncated to days-precision:
auto local_day = floor<days>(zoned_time{tz, now}.get_local_time());
Now a local time_point can be created simply by summing local_day and local_config_tod. This local time_point can then be converted back into UTC (a time_point based on system_clock but with seconds precision):
auto utc_config = zoned_time{tz, local_day + local_config_tod}.get_sys_time();
The line of code above handles the corner cases for you. If there is not a unique (one-to-one) mapping from local time to UTC, then an exception is thrown. The .what() of the exception type will have a detailed description about how this mapping is either ambiguous, or non-existent.
Assuming the above mapping does not throw an exception, you can simply compare these two UTC time_points:
return now < utc_config;
The precision of this comparison is with whatever precision your system_clock has (typically microseconds to nanoseconds).
This can be exercised like so:
int hour_ = 14;
int min_ = 32;
using namespace std::chrono;
auto b = is_now_before(hours{hour_} + minutes{min_});
If 14 and 32 are literals (and you're in C++14 or later), it can be shortened to:
auto b = is_now_before(14h + 32min);
If you are using a standard prior to C++17, the zoned_time constructions will require an explicit template parameter:
auto local_day = floor<days>(zoned_time<system_clock::duration>{tz, now}.get_local_time());
auto utc_config = zoned_time<minutes>{tz, local_day + local_config_tod}.get_sys_time();
If you would like to use the free, open-source C++20 chrono preview library, add #include "date/tz.h" and using namespace date;. Some installation is required.
If you would like to avoid an exception in the case that local_day + local_config_tod does not have a unique mapping to UTC, that is also possible with minor changes to is_now_before. But you will have to decide things such as: Do I want to compare against the first or second local_config_tod of the local_day (in case the UTC offset has been decreased).
Oops! Is the config time already UTC?
On re-reading your question it occurred to me that I may have misread your question. If 14:32 is UTC, then things get much, much simpler! And rather than removing my answer showing the local 14:32 interpretation, I thought it would be better to add this, so future readers could pick either solution.
Assuming the config is a UTC time, then time zones play no role at all:
#include <chrono>
bool
is_now_before(std::chrono::minutes utc_config_tod)
{
using namespace std::chrono;
auto now = system_clock::now();
auto utc_day = floor<days>(now);
return now < utc_day + utc_config_tod;
}
The current day in UTC is simply:
auto utc_day = floor<days>(now);
And now the config date-time is simply utc_day + utc_config_tod. This is just drop-dead simple.
If you can't use C++20, the free, open-source C++20 chrono preview library is also much simpler now as it is header-only, requiring no installation at all. Just #include "date/date.h" and add using namespace date;.
In C++ we can use the mt_structure from the date/time functions (documentation here: https://en.cppreference.com/w/cpp/chrono/c/tm) Here is how I would print the date, and check to see if it's past a certain time
#include <iostream>
#include <ctime>
#include <chrono>
using namespace std;
int main()
{
time_t t = time(0); // get time now
tm* now = localtime(&t);
cout << (now->tm_year + 1900) << '-'
<< (now->tm_mon + 1) << '-'
<< now->tm_mday << ", "
<< now->tm_hour << ":" << now->tm_min
<< "\n";
int hour = 7, minute = 30;
if((now->tm_hour > hour) || (now->tm_hour == hour && now->tm_min >= minute))
cout << "it's past 7:30\n";
else
cout << "it's not past 7:30";
}
prints:
2021-10-27, 20:40
it's past 7:30
I am using iso_week.h from howardhinnant.github.io/iso_week.html to calculate the week number for a given date. However, it looks that it updates the week number on Monday at 3 a.m., instead of midnight.
For example code like this:
#include <iostream>
#include "iso_week.h"
int main() {
using namespace iso_week;
using namespace std::chrono;
/* Assume we have two time points:
* tp1 corresponds: Monday July 15 02:50:00 2019
* tp2 corresponds: Monday July 15 03:00:00 2019
*/
// Floor time points to convert to the sys_days:
auto tp1_sys = floor<days>(tp1);
auto tp2_sys = floor<days>(tp2);
// Convert from sys_days to iso_week::year_weeknum_weekday format
auto yww1 = year_weeknum_weekday{tp1_sys};
auto yww2 = year_weeknum_weekday{tp2_sys};
// Print corresponding week number of the year
std::cout << "Week of yww1 is: " << yww1.weeknum() << std::endl;
std::cout << "Week of yww2 is: " << yww2.weeknum() << std::endl;
}
The output is:
Week of yww1 is: W28
Week of yww2 is: W29
Why is this being done?
At first I didn't notice your comment:
// Floor time points to convert to the sys_days:
This means that tp1 and tp2 are based on system_clock. And system_clock models UTC.
You can use the tz.h header (tz.cpp source) to get your current time zone, convert the UTC time points to local time points, and then feed them to year_weeknum_weekday. This will define the start of the day as your local midnight instead of midnight UTC.
This would look something like:
#include "date/iso_week.h"
#include "date/tz.h"
#include <iostream>
int
main()
{
using namespace iso_week;
using namespace date;
using namespace std::chrono;
auto tp1 = floor<seconds>(system_clock::now());
zoned_seconds zt{current_zone(), tp1};
auto tp1_local = floor<days>(zt.get_local_time());
auto yww1 = year_weeknum_weekday{tp1_local};
std::cout << "Week of yww1 is: " << yww1.weeknum() << std::endl;
}
current_zone() queries your computer for its current local time zone setting. If you prefer some other time zone, you can just replace current_zone() with the time zone name:
zoned_seconds zt{"Europe/Athens", tp1};
If you want to work in a precision finer than seconds, zoned_seconds is just a type alias for zoned_time<seconds>. So use whatever precision you need (e.g. zoned_time<milliseconds>).
Use of tz.h does require some installation. It is not header only.
Could this have something to do with your time zone? I know a lot of businesses are located on the east coast and "iso_week.h" could be based on that time, meaning it could be running at midnight and it just tells you that it is running at 3am. If this is not the case would it be wrong to just run the program at 9pm?
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>.
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;
}
I've got a problem with getting actual system time with milliseconds. The only one good method I found is in Windows.h, but I can't use it. I'm supposed to use std::chrono. How can I do this?
I spent a lot of time trying to google it, but I found only second-precision examples.
I'm trying to get string like this:
[2014-11-25 22:15:38:449]
Using code from this answer:
#include <chrono>
#include <ctime>
#include <iostream>
template <typename Duration>
void print_time(tm t, Duration fraction) {
using namespace std::chrono;
std::printf("[%04u-%02u-%02u %02u:%02u:%02u.%03u]\n", t.tm_year + 1900,
t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec,
static_cast<unsigned>(fraction / milliseconds(1)));
// VS2013's library has a bug which may require you to replace
// "fraction / milliseconds(1)" with
// "duration_cast<milliseconds>(fraction).count()"
}
int main() {
using namespace std;
using namespace std::chrono;
system_clock::time_point now = system_clock::now();
system_clock::duration tp = now.time_since_epoch();
tp -= duration_cast<seconds>(tp);
time_t tt = system_clock::to_time_t(now);
print_time(*gmtime(&tt), tp);
print_time(*localtime(&tt), tp);
}
One thing to keep in mind is that the fact that the timer returns values of sub-millisecond denominations does not necessarily indicate that the timer has sub-millisecond resolution. I think Windows' implementation in VS2015 may finally be fixed, but the timer they've been using to back their chrono implementation so far has been sensitive to the OS timeBeginPeriod() setting, displaying varying resolution, and the default setting is I think 16 milliseconds.
Also the above code assumes that neither UTC nor your local timezone are offset from the epoch of std::chrono::system_clock by a fractional second value.
Example of using Howard's date functions to avoid ctime: http://coliru.stacked-crooked.com/a/98db840b238d3ce7
This answer still uses a bit of C API but is only used in the function, so you can forget about it:
template<typename T>
void print_time(std::chrono::time_point<T> time) {
using namespace std;
using namespace std::chrono;
time_t curr_time = T::to_time_t(time);
char sRep[100];
strftime(sRep,sizeof(sRep),"%Y-%m-%d %H:%M:%S",localtime(&curr_time));
typename T::duration since_epoch = time.time_since_epoch();
seconds s = duration_cast<seconds>(since_epoch);
since_epoch -= s;
milliseconds milli = duration_cast<milliseconds>(since_epoch);
cout << '[' << sRep << ":" << milli.count() << "]\n";
}
This is merely a rewrite of the code that bames53, but using strftime to shorten the code a bit.
std::chrono give you utilities to represent a point in time or the elapsed duration between two points in time. It allows you to get information about these time intervals.
It does not provide any calendar information. Unfortunately, at this time there are no tools in the C++ standard for these. boost::date_time may be helpful here.
Did anybody notice that to_time_t rounds the seconds, instead of truncating
auto now = system_clock::now();
time_t secs = system_clock::to_time_t(now);
now {_MyDur={_MyRep=15107091978759765 } }
secs = 1510709198
so when you tack on the milliseconds
auto tse = now.time_since_epoch();
auto now_ms = duration_cast<milliseconds>(tse);
auto now_s = duration_cast<seconds>(tse);
auto jst_ms = now_ms - now_s;
DWORD msecs = jst_ms.count();
msecs = 875
secs should be 1510709197, but look at now_s, it's right
now_s {_MyRep=1510709197 }