How to get the difference between two QDateTimes in milliseconds? - qt

I wish QDateTime overrode the - operator and returned a QTimeSpan representing the difference between two QDateTimes (just like .NET's TimeSpan). Since this doesn't exist in Qt, I decided to implement it.
Unfortunately, QDateTime has no msecsTo-like function. What is the cleanest way to get the difference between two QDateTimes accurate to the millisecond?

I realize that this question is from 2010, and that Qt 4.7 didn't exist back then (it actually came out about a week after this question was originally asked--September 21 2010), but for people who are looking for how to do this now:
As of Qt 4.7, QDateTime has a "msecsTo" method. See Qt 4.8 documentation at http://doc.qt.io/qt-4.8/qdatetime.html#msecsTo.
QDateTime dateTime1 = QDateTime::currentDateTime();
// let's say exactly 5 seconds pass here...
QDateTime dateTime2 = QDateTime::currentDateTime();
qint64 millisecondsDiff = dateTime1.msecsTo(dateTime2);
// millisecondsDiff is equal to 5000

I would probably use a.daysTo(b)*1000*60*60*24 + a.time().msecsTo(b.time()). Note that you need to watch how close you can be, since you're going to overflow your data type rather quickly.

how about this:
QDateTime a = QDateTime::currentDateTime();
QDateTime b = a.addMSecs( 1000 );
qDebug( "%d", a.time().msecsTo( b.time() ) );
Source

All the solutions are good, but if your timestamp is in a particular format then you can find the difference by below, and also you can assign that to QString.
let start is time on some moment in some format
QString start = QDateTime().currentDateTime().toString("hh:mm:ss AP dd/MM/yyyy");
let end is time on some moment after start in some format
QString end = QDateTime().currentDateTime().toString("hh:mm:ss AP dd/MM/yyyy");
So, you can find the difference by providing the format and using msecsto and assign them to QString(if required).
QString timeDiff= QString("%1").arg(QDateTime().fromString(start ,"hh:mm:ss AP dd/MM/yyyy").msecsTo(QDateTime().fromString(end ,"hh:mm:ss AP dd/MM/yyyy")));

Related

NetCDF-Java: how to write unsigned attribute?

I'm trying to write an unsigned value to a valid_range attribute in an nc4 file using NetCDF-Java 4.3, but it is always written as signed. This makes viewing applications display the data incorrectly. Sample code:
Array array = Array.factory(DataType.byte, new int[] { 2 });
array.setUnsigned(true);
array.setObject(0, 0);
array.setObject(1, 255);
Attribute attr = new Attribute("valid_range", array);
log.debug("{}", attr);
This prints out:
valid_range = 0UB, -1UB
But the CDL for that attribute in the resulting file is:
colour1:valid_range = 0b, -1b ;
When I look at that variable in ToolsUI 4.3, it's all blank because everything is outside of the false range. I tried using shorts to represent unsigned bytes; that works for valid_range but fails for the _FillValue attribute:
WARN Nc4Iosp - _FillValue type must agree with var = colour2 type short!=byte
How should unsigned types be written to attributes?
Netcdf-Java stable version is 4.6, and 4.3 is pretty out of date, esp for writing to netcdf4. So you should see how/if 4.6 works.
Netcdf-Java version 5 has added unsigned data types to make this easier, though thats not yet stable.
Widening valid_range is a good solution. You must leave _FillValue as the same type as the variable, though as you noted.
Why do you want to set valid_range? IMO, its not a good practice, because it forces client software to check for validity. Dont use it unless you really need it. Documenting the actual_range is more useful.
If the variable is unsigned the valid_range values should be widened and stored as unsigned integers.
Array array = Array.factory(DataType.byte, new int[] { 2 });
Change that to...
Array array = Array.factory(DataType.INT, new int[] { 2 });
This came from Unidata's website.
https://www.unidata.ucar.edu/software/netcdf/docs/BestPractices.html

QDateTime to QString with milliseconds in Qt3

Is there a way in Qt3 to convert QDateTime into a QString and back to QDateTime, so that eventually QDateTime will contain information about milliseconds?
Thanks.
Use the toString function. The format parameter determines the format of the result string.
For example the following code will return only the seconds and the miliseconds.
QDateTime t = QDateTime::currentDateTime ();
QString s = t.toString("ss:zzz");
PS. You should consider porting your code to Qt4
QString DataList[100][100] ;
QDateTime AwbDateTime ;
AwbDateTime = QDateTime::fromString(DataList[i][9].left(19),Qt::ISODate) ;
This will work fine in Qt3

How do I get milliseconds in a QDateTime with QSqlQuery in Qt C++?

I have this sql query:
SELECT LOG_TIME FROM PCY_LOG_EVENTS;
This returns data in the format "DD-MMM-YY HH.MM.SS.MS" like this:
30-OCT-11 09.00.57.638000000 AM
In my Qt code, I have this:
QSqlQuery query("SELECT LOG_TIME from PCY_LOG_EVENTS", db);
while(query.next()) {
//Displays a QMessageBox with the millisecond part of the QDateTime
this->messageBox(QString::number(query.value(0).toDateTime().time().msec()));
}
I get 0 for all the millisecond values. Is there a reason why the millisecond values are not being stored? How would I get the millisecond values?
Get the query value as a QString
QString dateTimeString = query.value(0).toString();
Then use the static fromString function of the QDateTime. You have to specify the format of your string. I assume the days of the month have a leading zero
QDateTime dateTime = QDateTime::fromString(dateTimeString, "dd-MMM-yy hh.mm.ss.zzz000000 A")
Notice the milliseconds part :zzz000000. Since the max value can be 999 the trailing zeros of your example make no sense. So by using the zzz followed by the zeros you can get the miliseconds stored in your string. The only possible problem is that your month part uses upper case letters while the MMM returns the month abbreviation with just the first letter capitalized. I hope there won't be a problem with it.
Once you do the conversion you can easily get the milliseconds:
int ms = dateTime.time().msec();
For more formatting options here

Converting QString containing PostgreSQL timestamp to QDateTime

I'm having trouble with a seemingly very simple problem: I want to get a QDateTime from a QString containing a timestamp. I got the timestamp from PostgreSQL, but it doesn't matter. Here is the code that does not work:
QString timestamp = "2010-10-09 19:21:46+02:00";
QString format = "YYYY-MM-DD HH:MM:SSTZD";
QDateTime dt = QDateTime::fromString(timestamp, format);
qDebug() << dt.toString(); // outputs empty string
There must be something very obvious I'm missing. Thanks!
There were two mistakes I was making. There is no TZD in the format specifications, so I removed the time zone information since I do not need it in my app by doing:
timeStamp.chop(6);
And then used the following format to get a QDateTime. Note the lowercase format characters:
QDateTime createdAt = QDateTime::fromString(timeStamp, "yyyy-MM-dd HH:mm:ss");
Thanks to everyone above for helping out.

How to convert from timestamp to date in Qt?

I have a Unix timestamp and I need to convert it to human readable date + time. How can it be done in Qt?
int unixTime = 1234567890;
QDateTime timestamp;
timestamp.setTime_t(unixTime);
qDebug() << timestamp.toString(Qt::SystemLocaleShortDate);
That should get you going. Like Matthew said, see QDateTime.setTime_t, as well as QDateTime.toString. The toString has an enumeration with several different options, as well as an overload where you can pass a string allowing however much customization you like.
QDateTime.setTime_t
You can use the static function: "fromTime_t", like:
qDebug() << QDateTime::fromTime_t(your_time_stamp).toString("dd/MM/yyyy hh:mm:ss");
One good example
qint64 qiTimestamp=QDateTime::currentMSecsSinceEpoch();
QDateTime dt;
dt.setTime_t(qiTimestamp/1000);
ui->lineEdit_DateTime->setText(dt.toString("yyyy-MM-dd hh:mm:ss"));
Note that QDateTime::setTime_t() has been deprecated, use QDateTime::setSecsSinceEpoch(). Same for fromTime_t(): use QDateTime::fromSecsSinceEpoch().
As mentioned, instead of using the obsolete _t members here is a working example (Qt 5).
qint64 llTS=1591132400;
QString szFull=QDateTime::fromSecsSinceEpoch(llTS).toString("dddd d MMMM yyyy hh:mm:ss");
szFull: Tuesday 2 June 2020 23:13:20
Source: QDateTime (Qt 5)
Date formatting: QDate
Time formatting: QTime

Resources