Question

I'm trying to convert a time stamp in string format to msecs since epoch, like so:

QString startTime("20131030 21923"); //2013-10-30 02:19:23 
auto date = QDateTime::fromString(startTime, "yyyyMMdd hmmss");
auto secsSinceEpoch = date.toTime_t();

The result (secsSinceEpoch) is 1383163763, which converts to 2013-10-30 21:09:23. So it seems like my format string is interpreted incorrectly (as "yyyyMMdd hhmss"), why is that so and what can I do to solve this?

Was it helpful?

Solution 2

see the caveat here: http://qt-project.org/doc/qt-5.0/qtcore/qdate.html#fromString-2

The expressions that don't expect leading zeroes (d, M) will be greedy. This means that they will use two digits even if this will put them outside the accepted range of values and leaves too few digits for other sections. For example, the following format string could have meant January 30 but the M will grab two digits, resulting in an invalid date:

so your best be it to split them up and parse separately

edit: for example you can get the date and time with

QDate date = QDate::fromString(startTime.left(8), "yyyMMdd");
startTime[8]=0;//replacing the " " with a 0
QTime time = QTime::fromString(startTime.right(6), "hhmmss");//hour becomes a 2 digit
QDateTime fullDate(date,time);
auto secsSinceEpoch = fullDate.toTime_t();

OTHER TIPS

According to the documentation of QDateTime, "h" means "the hour without a leading zero" and "hh" means "the hour with a leading zero". So the number of "h" does not necessarily correspond to the number of digits, as in strftime :)

A workaround would be to parse the timestamp into a time_t with std C/C++ functions. Or just add a space between 2 and 1923 and change the expression in fromString accordingly.

'h' stands for "hour without leading zero". I think there is a logical fallacy in qt documents in http://harmattan-dev.nokia.com/docs/library/html/qt4/qdatetime.html

"21923" would stand for 2:19:23 when "mm" is parsed before "h" is. But I guess QT calculates from left to right and 21 is perfectly valid hour value. If it was "31923", your assumptions would be correct, though.

I'd go for a blank char ' ' or semicolon between h and m values if you want to avoid leading zeros.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top