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).
Related
This question already has answers here:
How to get current time and date in Android
(42 answers)
Closed 6 years ago.
#include "stdafx.h"
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
time_t now = time(NULL);
int sec = now % 60;
int min = ((now - sec) / 60) % 60;
int hour = ((((now - sec) / 60) - min) / 60) % 24;
int day = ((((((now - sec) / 60) - min) / 60) - hour) / 24) % 30;
int month = ((((((((now - sec) / 60) - min) / 60) - hour) / 24) - day) / 30) % 12;
int year = ((((((((((now - sec) / 60) - min) / 60) - hour) / 24) - day) / 30) - month) / 12) + 1970;
cout << hour << ":" << min << ":"<< ":" << day << ":" << month << ":" << year<<endl;
}
I can't understand why month output 10 instead of 3 ???
(I know there is c_time function but i am learning and making my own one)
time() function returns a number of seconds since January 1st, 1970.
Converting this into a date is much more complex than you think:
It starts with calculating the seconds: taking the number %60 should in principle tell the seconds in the current minute. That seems obvious. But this is not exact: it doesn't take into account the 25 leap seconds that took place since 1970.
minutes, hours would be ok if you take into account this first correction (and eventually taking into account daylight saving time, if this code is not ran in winter)
your calculation of the day of the month does not take into account the fact that not all the months are 30 days long, and it doesn't take into account the leap years.
And basically, the calculation of the months and the year would be affected by the impact of the wrong estimation of month.
Do yourself a favour and convert the date using a standard function like gmtime() or localtime() and accessing the fields of the struct tm
Converting seconds to days/hours/minutes is trivial. Converting days since 1970 to current date is not. You either should use library functions if you can or you may use formula provided for Julian day, just pay attention that 1/1/1970 is not 0 for Julian day.
PS subtracting reminder is completely unnecessary:
int min = ((now - sec) / 60) % 60;
should be:
int min = now / 60 % 60;
or even better:
int sec = now % 60;
now /= 60;
int min = now % 60;
now /= 60;
and so on.
It is extremely daunting task of converting 'seconds since epoch' to day/month/year/etc.
This is why library got you covered. There are gmtime_r() and localtime()_r designed specifically for that. Unfortunately, those functions are not standard, and the only standard ones are thread unsafe gmtime() and localtime().
As I said in title I need to convert seconds to hh:mm:ss
I tried this:
ui->label->setText(QDateTime::fromTime_t(10).toString("hh:mm:ss"));
But default value for hours is always 01 but I need it to be 00. As result I should get 00:00:10 but I get 01:00:10.
Your timezone is included in it thats why. Try this:
QDateTime::fromTime_t(10).toUTC().toString("hh:mm:ss");
There is no QTime::fromTime_t; possibly you're using QDateTime::fromTime_t, which accounts for time zones and daylight savings.
Instead you can use QTime().addSecs(10).toString(...).
Other answers work perfect when the number of seconds stays below 24 hours. For most usecases that is good enough. However for our usecase the timer went above 24 hours and reset to 00:00:00. Do note that the following code does not work for times of 100 hours or more. The number 2 in the arg method forces the string to be 2 characters.
int totalNumberOfSeconds = 90242; // nr of seconds more than 1 day.
int seconds = totalNumberOfSeconds % 60;
int minutes = (totalNumberOfSeconds / 60) % 60;
int hours = (totalNumberOfSeconds / 60 / 60);
QString timeString = QString("%1:%2:%3")
.arg(hours, 2, 10, QChar('0'))
.arg(minutes, 2, 10, QChar('0'))
.arg(seconds, 2, 10, QChar('0'));
In Qt 5 you can use QTime::fromMSecsSinceStartOfDay(int msecs).
ui->label->setText(QTime::fromMSecsSinceStartOfDay(10 * 1000).toString("hh:mm:ss"));
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);
I have a loop and in every loop I get the current seconds the application has been running for I then want to convert this time into how many, Days, Hours and Seconds that the seconds calculate to but not 'real time' I need to be able to customize how many seconds are in a day, I have tried examples on SO and the web but nothing seems to be out there for this. I have some defines
#define DAY 1200
#define HOUR DAY / 24
#define MINUTE HOUR / 60
#define SECOND MINUTE / 60
So in my define a day would last for 1200 seconds. I have then been trying to convert elapsed seconds into 'my' seconds
seconds_passed = fmodf(SECOND, (float)(GetTicks() / 1000));
Which returns what SECOND equals (0.013889) but then every loop is the same, it never changes I was thinking I would just be able to convert for example: 1real second into 1.25fake seconds then
Minute = (seconds_passed / MINUTE);
seconds_passed = fmodf(seconds_passed, MINUTE);
work out how many (fake)minutes, (fake)hours and (fake)days have elapsed since the application started.
Hope that makes sense, thank you for your time.
Since you want to customise how many seconds are in a day, all you're really doing is changing the ratio of 1 second : 1 second.
For instance, if you did was 1200 seconds in a day your ratio is:
1:72
that is, for every 1 second that passes in your day, it is the equivilent of 72 real seconds.
So yes basically all you need to do in your program is find the ratio of 1 second to 1 second, times your elapsed seconds by that to get the 'fake' seconds, and then use that value...
The code may look something like this:
// get the ratio second:fake_second
#define REAL_DAY_SECONDS 86400
int ratio = REAL_DAY_SECONDS / DAY;
fake_to_real = fake_second*ratio;
real_to_fake = real_second/ratio;
You can make your own time durations with one line in chrono:
using fake_seconds = std::chrono::duration<float, std::ratio<72,1>>;
Some sample code
#include <iostream>
#include <chrono>
using namespace std::chrono_literals;
using fake_seconds = std::chrono::duration<float, std::ratio<72,1>>;
int main()
{
auto f_x = fake_seconds(350s);
std::cout << "350 real seconds are:\n" << f_x.count() << " fake_seconds\n";
}
https://godbolt.org/z/f5G86avxr
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);