I want to see whether my data is 120 second old by looking at the timestamp of the data so I have below code:
uint64_t now = duration_cast<milliseconds>(steady_clock::now().time_since_epoch()).count();
bool is_old = (120 * 1000 < (now - data_holder->getTimestamp()));
In the above code data_holder->getTimestamp() is uint64_t which returns timestamp in milliseconds. Does my above code looks right?
I'd probably do something like this:
auto now = system_clock::now().time_since_epoch();
// Use the correct time duration below. Milliseconds could be wrong, see 1)
auto diff = now - std::chrono::milliseconds(data_holder->getTimestamp());
bool is_old = diff > std::chrono::seconds{120};
// bool is_old = diff > 120s; // From C++14 onwards.
1) As mentioned, milliseconds could be the wrong unit to use for getTimestamp(). All possible types are
std::chrono::hours
std::chrono::minutes
std::chrono::seconds
std::chrono::milliseconds
std::chrono::microseconds
std::chrono::nanoseconds
You probably have to try out which one to use, because that depends on data_holder->getTimestamp().
Note: Big one
Making sure to use system_clock to measure time since epoch will work most likely. But the standard doesn't require that a clock's epoch is the UNIX epoch. You have encountered this with steady_clock already.
You'd have to calculate the difference between the clock's epoch and the epoch yourself (and I don't know of a way to do that right now for any clock). For system_clock, if you don't trust it to use the unix epoch you can use the following:
system_clock::duration time_since_unix_epoch()
{
std::tm epoch;
epoch.tm_mday = 1;
epoch.tm_mon = 0;
epoch.tm_year = 70;
std::time_t epocht = mktime(&epoch);
return system_clock::now() - system_clock::from_time_t(epocht);
}
instead of system_clock::now(). I'd prefer this method.
Unfortunatly you can't just replace system_clock with another clock from std::chrono because only std::system_clock offers from_time_t(time_t) which converts a real date to the internal time_point used by the clock.
Related
I'm using C++14 and the famous Date library by #HowardHinnant
I'm trying to convert a GMT (UTC) time to the time inside of some timezone. I need to have it in the tm struct.
All seems good except I can't seem to properly construct the hms object. My template arguments mismatch.
tm Time_hrv::gmtTM_to_timezoneTM(const tm& timeTM_gmt, const std::string& wanted_timezoneStr){
assert(timeTM_gmt.tm_year < 1000);// the year of tm should be relative to 1900. For example, 2020 should be 120.
assert(timeTM_gmt.tm_mon < 12);// [0,11]
assert(timeTM_gmt.tm_mday > 0 && timeTM_gmt.tm_mday<=31);// [0,31]
time_t timeT_gmt = Time_hrv::timeTM_to_timeT(timeTM_gmt);
auto chronoTime_gmt = std::chrono::system_clock::from_time_t(timeT_gmt);
const date::time_zone* wanted_timeZone = timeZone_fromString(wanted_timezoneStr);
//https://stackoverflow.com/a/70759851/9007125
//NOTICE: local_time isn't necessarily the computer's local time.
//It is a local time that has not yet been associated with a time zone.
//When you construct a zoned_time, you associate a local time with a time zone.
auto lt = wanted_timeZone->to_local(chronoTime_gmt);
auto localDay = date::floor<date::days>(lt);
date::year_month_day ymd{ localDay };
date::hh_mm_ss<std::chrono::milliseconds> hms{ lt - localDay }; //<--- error here
tm result = {0};
result.tm_year = int{ymd.year()} - 1900;
result.tm_mon = unsigned{ymd.month()} -1;
result.tm_mday = unsigned{ymd.day()};
result.tm_hour = (int)hms.hours().count();
result.tm_min = (int)hms.minutes().count();
result.tm_sec = (int)hms.seconds().count();
return result;
}
This is chrono giving you a bad error message for a real problem: You are attempting to silently truncate a fine precision expression (lt - localDay) to a coarser precision (milliseconds).
The expression lt - localDay is a type that has precision of system_clock::duration, which is somewhere between microseconds and nanoseconds depending on your platform. This is true, even though the source (and thus the value) of chronoTime_gmt only has precision of seconds at run time.
The easiest fix is to recognize that anything coming from a tm is at best seconds precision by truncating to seconds precision early:
auto chronoTime_gmt = date::floor<std::chrono::seconds>
(std::chrono::system_clock::from_time_t(timeT_gmt));
Now chronoTime_gmt has type time_point<system_clock, seconds>. And therefore the later expression lt - localDay will also have type seconds, which will implicitly convert to the milliseconds precision of your hh_mm_ss.
A suggestion is to also use seconds for the template parameter of your hh_mm_ss since the milliseconds precision goes unused. This won't change correctness or performance of your code, but the reader of your code will no longer spend time wondering why you chose milliseconds and then didn't use it.
Let's say I have a stream of events, each event with a full timestamp, spanning many days. I want to compare them against the time of day, but regardless of the day. For example, if a given event happened between 12:00:00 and 12:05:00, do something, but regardless of the day.
The event timestamps naturally fit as std::chrono::time_point objects. What is the most idiomatic way within std::chrono to do those comparisons? Is there an object that represents a time-of-day without being specific to a day? Do I have to roll my own?
You may do something like:
auto timePoint = std::chrono::system_clock::now();
std::time_t t = std::chrono::system_clock::to_time_t(timePoint);
auto ltime = std::localtime(&t); // or gmtime.
auto eventTime = std::chrono::hours(ltime->tm_hour)
+ std::chrono::minutes(ltime->tm_min);
auto lower_bound = std::chrono::hours(12) + std::chrono::minutes(0);
auto upper_bound = std::chrono::hours(12) + std::chrono::minutes(5);
if (lower_bound <= eventTime && eventTime <= upper_bound) {
// Do some action.
}
Is there an object that represents a time-of-day without being specific to a day? Do I have to roll my own?
I don't think so. But it should be trivial to implement. Convert the timepoint to the broken-down time std::tm, and then check the individual members.
#include <chrono>
#include <ctime> // struct tm, gmtime()
using std::chrono::system_clock;
std::time_t ts = system_clock::to_time_t (system_clock::now());
std::tm& time = *gmtime (&ts); // or localtime()
if (time.tm_hour==12 and time.tm_min>=0 and time.tm_min<5)
cout << "Inside interval\n";
Note: gmtime() and localtime() return a pointer to static data and hence are not thread-safe. Linux (and probably other *nix) has the thread safe gmtime_r() and localtime_r().
My current pattern (for unix) is to call gettimeofday, cast the tv_sec field to a time_t, pass that through localtime, and combine the results with tv_usec. That gives me a full date (year, month, day, hour, minute, second, nanoseconds).
I'm trying to update my code to C++11 for portability and general good practice. I'm able to do the following:
auto currentTime = std::chrono::system_clock::now( );
const time_t time = std::chrono::system_clock::to_time_t( currentTime );
const tm *values = localtime( &time );
// read values->tm_year, etc.
But I'm stuck on the milliseconds/nanoseconds. For one thing, to_time_t claims that rounding is implementation defined (!) so I don't know if a final reading of 22.6 seconds should actually be 21.6, and for another I don't know how to get the number of milliseconds since the previous second (are seconds guaranteed by the standard to be regular? i.e. could I get the total milliseconds since the epoch and just modulo it? Even if that is OK it feels ugly).
How should I get the current date from std::chrono::system_clock with milliseconds?
I realised that I can use from_time_t to get a "rounded" value, and check which type of rounding occurred. This also doesn't rely on every second being exactly 1000 milliseconds, and works with out-of-the-box C++11:
const auto currentTime = std::chrono::system_clock::now( );
time_t time = std::chrono::system_clock::to_time_t( currentTime );
auto currentTimeRounded = std::chrono::system_clock::from_time_t( time );
if( currentTimeRounded > currentTime ) {
-- time;
currentTimeRounded -= std::chrono::seconds( 1 );
}
const tm *values = localtime( &time );
int year = values->tm_year + 1900;
// etc.
int milliseconds = std::chrono::duration_cast<std::chrono::duration<int,std::milli> >( currentTime - currentTimeRounded ).count( );
Using this free, open-source library you can get the local time with millisecond precision like this:
#include "tz.h"
#include <iostream>
int
main()
{
using namespace date;
using namespace std::chrono;
std::cout << make_zoned(current_zone(),
floor<milliseconds>(system_clock::now())) << '\n';
}
This just output for me:
2016-09-06 12:35:09.102 EDT
make_zoned is a factory function that creates a zoned_time<milliseconds>. The factory function deduces the desired precision for you. A zoned_time is a pairing of a time_zone and a local_time. You can get the local time out with:
local_time<milliseconds> lt = zt.get_local_time();
local_time is a chrono::time_point. You can break this down into date and time field types if you want like this:
auto zt = make_zoned(current_zone(), floor<milliseconds>(system_clock::now()));
auto lt = zt.get_local_time();
local_days ld = floor<days>(lt); // local time truncated to days
year_month_day ymd{ld}; // {year, month, day}
time_of_day<milliseconds> time{lt - ld}; // {hours, minutes, seconds, milliseconds}
// auto time = make_time(lt - ld); // another way to create time_of_day
auto y = ymd.year(); // 2016_y
auto m = ymd.month(); // sep
auto d = ymd.day(); // 6_d
auto h = time.hours(); // 12h
auto min = time.minutes(); // 35min
auto s = time.seconds(); // 9s
auto ms = time.subseconds(); // 102ms
Instead of using to_time_t which rounds off you can instead do like this
auto tp = std::system_clock::now();
auto s = std::chrono::duration_cast<std::chrono::seconds>(tp.time_since_epoch());
auto t = (time_t)(s.count());
That way you get the seconds without the round-off. It is more effective than checking difference between to_time_t and from_time_t.
I read the standard like this:
It is implementation defined whether the value is rounder or truncated, but naturally the rounding or truncation only occurs on the most detailed part of the resulting time_t. That is: the combined information you get from time_t is never more wrong than 0.5 of its granularity.
If time_t on your system only supported seconds, you would be right that there could be 0.5 seconds systematic uncertainty (unless you find out how things were implemented).
tv_usec is not standard C++, but an accessor of time_t on posix. To conclude, you should not expect any rounding effects bigger than half of the smallest time value difference your system supports, so certainly not more than 0.5 micro seconds.
The most straight forward way is to use boost ptime. It has methods such as fractional_seconds()
http://www.boost.org/doc/libs/1_53_0/doc/html/date_time/posix_time.html#date_time.posix_time.ptime_class
For interop with std::chrono, you can convert as described here: https://stackoverflow.com/a/4918873/1149664
Or, have a look at this question: How to convert std::chrono::time_point to calendar datetime string with fractional seconds?
My goal is to determine expiry of an item to when it was acquired(bought) and when it is sold.There is a TTL value associated with each of the item.
I am doing following :
time_t currentSellingTime;
long currentSystemTime = time(¤tSellingTime); // this gives me epoch millisec of now()
long TTL = <some_value>L;
long BuyingTime = <some_value> // this is also in epoch millsec
if(currentSystemTime > TTL+BuyingTime))
{
//throw exception
// item is expired
}
My question is how to sum two epoch millisec and compare it with another epoch millsec in C++
There may be some misconceptions on how time() works:
epoch time as given by time() is expressed in seconds, not millseconds
time returns the current time value and can optionally set current time in the variable given as its sole argument. This means that
long currentSystemTime = time(¤tSellingTime);
will set both currentSystemTime and currentSellingTime to the current time, and that's probably not what you intend to do... You should probably do
long currentSystemTime = time(NULL);
or
time(¤tSellingTime);
but the "double form" you are using is quite suspicious. For completeness' sake the MS Help reference for time()
You want to use another function, as as previously pointed out, time() returns seconds. Try:
#include <time.h>
long current_time() {
struct timespec t;
clock_gettime(CLOCK_REALTIME, &t);
return t.tv.sec * 1000l + t.tv_nsec / 1000000l;
}
Your code should work then. This approach is also POSIX compatible. Example usage:
const long TTL = 100;
long start_time = current_time();
while (!(current_time() > start_time + TTL))
{
// do the stuff that can expire
}
note: I know that the condition in the while loop can be constructed differently, but this way it is more like "until not expired".
I've seen some other answers on SO that suggest we can get the time from epoch in milliseconds by subtracting the epoch time from the "other" time, but it doesn't work when I try it:
ptime epoch = time_from_string("1970-01-01 00:00:00.000");
ptime other = time_from_string("2011-08-09 17:27:00.000");
long diff = (other-epoch).total_milliseconds();
At this stage diff is -1349172576 and it should be a positive number since the "other" time is 2011. Does anybody know what might be causing this? What's the proper way to get the milliseconds since epoch?
Additionally, I've tried to construct a ptime object from milliseconds:
ptime result = from_time_t(diff);
Result then becomes: "1927-Apr-01 13:50:24" and it should be "2011-Aug-09 17:27:00.000". What's the catch here?
Update:
OK, so my mistake stems from the fact that I have 2 programs, one is C# (8 byte/64-bit long) and a C++ (4 byte/32-bit long); in any case, that interaction is not depicted here.
However, when I use long long, the value is positive but the resulting date (constructed from_time_t) is still incorrect: "2012-Oct-02 10:09:36".
Presumably you're on a platform on which long is smaller than 64 bits.
Let's assume it's 32 bits – in that case, the maximum value of a long is 2147483648. However, it's been ~1312000000000 milliseconds since epoch, so long is clearly insufficient to hold this value and consequently you're seeing overflow.
I'd do something like this instead:
ptime epoch = time_from_string("1970-01-01 00:00:00.000");
ptime other = time_from_string("2011-08-09 17:27:00.000");
time_duration const diff = other - epoch;
long long ms = diff.total_seconds();
ms *= 1000LL;
ms += diff.fractional_seconds() / 1000000L; // 1000L if you didn't build datetime
// with nanosecond resolution
Creating a ptime from the specified number of milliseconds has the same problem – ptime works in terms of long and you have a long long – so you'll essentially need to do the reverse:
// given long long ms
time_duration t = seconds(static_cast<long>(ms / 1000LL));
if (ms % 1000LL)
t += milliseconds(static_cast<long>(ms % 1000LL));
A shortened variation on ildjarn's great solution:
ptime epoch = time_from_string("1970-01-01 00:00:00.000");
ptime other = time_from_string("2011-08-09 17:27:00.001");
time_duration const diff = other - epoch;
long long ms = diff.total_milliseconds();
This would be independent of whether it was built with nanosecond resolution.
you could try:
ptime other = time_from_string("2011-08-09 17:27:00.000");
time_t posix_time = (other - ptime(min_date_time)).total_seconds();