I know the Current system time.
I know the estimated time of arrival of a place in the form of hours minutes and seconds.
I need to find the duration of travel. But the estimated time of arrival is in 12 hour format.
I have to write a program to find the time difference between these two ?
I thought of using difftime(time1,time2)
but this requires the datatype time_t. I know the time in parts. i.e. i know the hours, minutes and seconds separatley. Both current system time and Estimated time of arrival.
I need to find the time difference between the two. The ETA can be after 24 hours. then is there any way i can find out the number of days of travel. Because after 12PM time is set back. hence i'm not able to keep track of the days.
Any solution ?
I work on C++
A straight forward way using C/C++. This is not very robust, but should meet your given requirements.
#include <ctime>
tm source;
memset(&source, 0, sizeof(tm));
tm.tm_hour = hour; // 24 hour format, 0 = midnight, 23 = 11pm
tm.tm_min = min;
tm.tm_sec = sec;
tm.tm_mon = month; // 0 based, 0 = jan, 11 = dec
tm.tm_mday = 10;
tm.tm.year = year; // current - 1900
time_t src_t = mktime(&source);
time_t now = time(NULL);
Related
I have specific date and time values in milliseconds detail such as;
year = 2020
month = 8 (August)
day = 5
hour = 15
minute = 45
second = 58
milliseconds = 997
I do not want to get the current date and time in milliseconds.
I need to convert these values to a total milliseconds value and add a milliseconds value such as 40 milliseconds to total milliseconds value. Then I need to convert the resulting milliseconds value to date and time again.
How can I do that? I came up with the following code, but there is no millisecond resolution in tm;
tm specTime;
specTime.tm_year = dataLine.year - 1900;
specTime.tm_mon = dataLine.month - 1;
specTime.tm_mday = dataLine.day;
specTime.tm_hour = dataLine.hour;
specTime.tm_min = dataLine.min;
specTime.tm_sec = dataLine.sec;
time_t millis = mktime(&specTime);
uint64_t timestamp_nanoseconds = 634019142119225390;
time_t result = timestamp_nanoseconds / 1000000000;
struct tm * timeinfo = gmtime(&result);
struct tm dateInfo ;
dateInfo.tm_mday = timeinfo->tm_mday ;
dateInfo.tm_mon = timeinfo->tm_mon ;
dateInfo.tm_year = timeinfo->tm_year ;
dateInfo.tm_hour = 0 ;
dateInfo.tm_min = 0 ;
dateInfo.tm_sec = 0 ;
time_t NoOfSecInDate = mktime ( &dateInfo );
From the input timestamp in nanoseconds, we can get the date as shown in the code which got set in dateInfo structure. From that point, We need to find elapsed time in seconds from the midnight of the input date.
We get input as elapsed time in nanoseconds since epoch Jan 1 1970. Say for example , 634019142119225390. From that we extract date with time set to 00:00:00 , we need to find the elapsed time in unsigned integer representing elapsed time in nanoseconds since Unix epoch 00:00 UTC on 1st January 1970 from midnight of that date.
Solution should be for any given timestamp and not for a current date.
In this above code , we find that mktime function takes about 64 microseconds to complete which is lot of time and is not expected
Do you have any other alternative to mktime function which achieves the same result that returns the elapsed time in seconds since epoch but with lesser amount of time.
This can be done highly efficiently with <chrono> and Howard Hinnant's free, open-source, date-time library.
Given:
uint64_t timestamp_nanoseconds = 634019142119225390;
Form a std::chrono::time_point based on system_clock and nanoseconds. The date-time library makes that very easy with a template type alias for such types:
sys_time<nanoseconds> ts{nanoseconds{timestamp_nanoseconds}};
Next you can truncate this nanosecond-precision time_point to a days precision time_point with:
auto sd = floor<days>(ts);
sd is a system_clock time_point counting days since the epoch (as opposed to nanoseconds). Next you can convert sd into a year_month_day, which is exactly what it sounds like: a {year, month, day} struct with getters for each field:
year_month_day ymd = sd;
And the relevant part for this question, this is how you get nanoseconds since midnight:
auto tod = ts - sd;
And if you want that in terms of seconds, it
auto tod = duration_cast<seconds>(ts - sd);
In all, to go from a uint64_t count of nanoseconds, to seconds in current day (UTC), and time it, it is:
auto t0 = steady_clock::now();
sys_time<nanoseconds> ts{nanoseconds{timestamp_nanoseconds}};
auto tod = duration_cast<seconds>(ts - floor<days>(ts));
auto t1 = steady_clock::now();
Given the input of 634019142119225390, and compiling this using clang on macOS at -O3, this results in:
tod == 15942s
and takes about 200ns.
This formulation will work correctly for both positive and negative inputs, due to the use of floor<days>, as opposed to duration_cast<days>. For example an input of -1'000'000'000 gives a time of day of 86399s.
You are trying to get the time at the start of the same UTC day. To do that, you can just do the calculation in seconds:
struct timezone tz = {0, 0};
struct timeval start, end;
gettimeofday(&start, &tz);
uint64_t timestamp_nanoseconds = 634019142119225390ULL;
time_t result = timestamp_nanoseconds / 1000000000ULL;
time_t day = result - (result % 86400);
gettimeofday(&end, &tz);
struct timeval dsec;
timersub(&end, &start, &dsec);
printf("calc took %ld sec %ld usec.\n",
dsec.tv_sec, dsec.tv_usec, s);
printf("UTC: %s",asctime(gmtime(&now)));
printf("Day: %s",asctime(gmtime(&day)));
This takes much less time:
calc took 0 sec 1 usec. total 0.000000
UTC: Sat Feb 3 04:25:42 1990
Day: Sat Feb 3 00:00:00 1990
If you want to get the start of the day in your local timezone you can add an offset to the calculation of day.
I'm using a code to save images from a camera, but I need to save the filename with the current date and time the image is taken. How can I do this? I have tried many different codes from the internet but I always get many errors and programming is not my strong side. Any advice or help will be appreciated. This is the code: https://github.com/stereolabs/zed-save-depth/blob/master/src/main.cpp
You can use:
#include <time.h>
for time. To get the current time :
time_t current_time = clock();
To get the current date, you can use :
struct tm *localtime(const time_t *time);
Which returns a struct for the local time that looks like this :
struct tm {
int tm_sec; // seconds of minutes from 0 to 61
int tm_min; // minutes of hour from 0 to 59
int tm_hour; // hours of day from 0 to 24
int tm_mday; // day of month from 1 to 31
int tm_mon; // month of year from 0 to 11
int tm_year; // year since 1900
int tm_wday; // days since sunday
int tm_yday; // days since January 1st
int tm_isdst; // hours of daylight savings time
}
I'm getting radar data as "tracks" and the track data indicates the number of UTC seconds since the last midnight, apparently. This is not the number of seconds since the 1st of jan 1970.
Now I want to convert that to date time, knowing that the clock on the computer could be slightly out of sync with the clock on the radar. I'll assume the radar's seconds are the reference, not the computer's.
I want to convert these seconds to a full date time. Things seem to be a little tricky around
midnight.
Any suggestions? I've got some ideas, but I don't want to miss anything.
I'm working with C++ Qt.
// Function to extend truncated time, given the wall time and period, all
// in units of seconds.
//
// Example: Suppose the truncated period was one hour, and you were
// given a truncated time of 25 minutes after the hour. Then:
//
// o Actual time of 07:40:00 results in 07:25:00 (07:40 + -15)
// o Actual time of 07:10:00 results in 07:25:00 (07:10 + +15)
// o Actual time of 07:56:00 results in 08:25:00 (07:56 + +29)
double extendTruncatedTime(double trunc, double wall, int period) {
return wall + remainder(trunc - wall, period);
}
#define extendTruncatedTime24(t) extendTruncatedTime(t, time(0), 24 * 60 * 60)
Some commentary:
The units of wall are seconds, but its base can be arbitrary. In Unix, it typically starts at 1970.
Leap seconds are not relevant here.
You need #include <math.h> for remainder().
The period in extendTruncatedTime() is almost always twenty-four hours, 24 * 60 * 60, as per the OP's request. That is, given the time of day, it extends it by adding the year, month, and day of month, based on the 'wall' time.
The only exception I know to the previous statement is, since you mention radar, is in the Asterix CAT 1 data item I001/141, where the period is 512 seconds, and for which extendTruncatedTime() as given doesn't quite work.
And there is another important case which extendTruncatedTime() doesn't cover. Suppose you are given a truncated time consisting of the day of month, hour, and minute. How can you fill in the year and the month?
The following code snippet adds the year and month to a time derived from a DDHHMM format:
time_t extendTruncatedTimeDDHHMM(time_t trunc, time_t wall) {
struct tm retval = *gmtime_r(&trunc, &retval);
struct tm now = *gmtime_r(&wall, &now);
retval.tm_year = now.tm_year;
retval.tm_mon = now.tm_mon;
retval.tm_mon += now.tm_mday - retval.tm_mday > 15; // 15 = half-month
retval.tm_mon -= now.tm_mday - retval.tm_mday < -15;
return timegm(&retval);
}
As written, this doesn't handle erroneous inputs. For example, if today is July 4th, then the non-nonsensical 310000 will be quietly converted to July 1st. (This may be a feature, not a bug.)
If you can link against another lib, i'd suggest to use boost::date_time.
It seems you want to take current date in seconds from midnight (epoch) then add the radar time to it, then convert the sum back to a date time, and transform it into a string.
Using boost will help you in:
getting the right local time
calculating the date back
incorporating the drift into the calculation
taking leap seconds into account
since you'll have concept like time intervals and durations at your disposal. You can use something like (from the boost examples):
ptime t4(date(2002,May,31), hours(20)); //4 hours b/f midnight NY time
ptime t5 = us_eastern::local_to_utc(t4);
std::cout << to_simple_string(t4) << " in New York is "
<< to_simple_string(t5) << " UTC time "
<< std::endl;
If you want to calculate the drift by hand you can do time math easily similar to constructs like this:
ptime t2 = t1 - hours(5)- minutes(4)- seconds(2)- millisec(1);
I had the exact same problem but I'm using C#. My implementation is included here if anyone needs the solution in C#. This does not incorporate any clock drift.
DateTime UTCTime = DateTime.UtcNow.Date.AddSeconds(secondSinceMidnightFromRadar);
using Qt 4.8 how can I print the time in the format DD HH SS? I have the seconds and I want to get back a string in that format.
QDateTime::fromTime_t(seconds).toString("ss hh DD");
see http://qt-project.org/doc/qt-5.0/qdatetime.html#toString
If you want a duration ( your question was really unclear) try something like :
QString seconds_to_DHMS(quint32 duration)
{
QString res;
int seconds = (int) (duration % 60);
duration /= 60;
int minutes = (int) (duration % 60);
duration /= 60;
int hours = (int) (duration % 24);
int days = (int) (duration / 24);
if((hours == 0)&&(days == 0))
return res.sprintf("%02d:%02d", minutes, seconds);
if (days == 0)
return res.sprintf("%02d:%02d:%02d", hours, minutes, seconds);
return res.sprintf("%dd%02d:%02d:%02d", days, hours, minutes, seconds);
}
Since you have the server uptime as seconds, you can use the QDateTime class.
QDateTime::fromTime_t(duration).toUTC().toString("dd hh ss");
Notice the toUTC, that's to set the beginning hour to 0. Since you will only be taking the date, hour and seconds, it doesn't really matter if the seconds are not since that date since the year won't be displayed.
You can use QDateTime::fromTime_t :
Returns a datetime whose date and time are the number of seconds that have passed since 1970-01-01T00:00:00, Coordinated Universal Time (Qt::UTC).
What you want to print is a duration of time...not a "moment" in clock time. QDateTime doesn't do much with durations except computing secsTo (and daysTo), and you pretty much have to roll your own printing.
Good news is the math isn't that hard:
Convert seconds to Days, Minutes and Seconds
Although your internationalization of words like seconds / days / years might be a nuisance. :(
The math is incredibly hard. Days are not 24 hours, they are usually 24 hours but sometimes 23 or 25 (daylight savings time changes) or 24 hours and a second or two (leap seconds). The same problem goes for months (obviously, since differently-sized months are common) years (leap day) and really anything that inherits day's problem by being defined in terms of days (weeks).