[Interest] QDateTime and std::chrono

Giuseppe D'Angelo giuseppe.dangelo at kdab.com
Fri Nov 2 17:50:47 CET 2018


Hi,

Il 02/11/18 16:40, Jérôme Godbout ha scritto:
> Maybe you can pass by a string, this would be highly inefficient but could be simple enough. I guess you should make the time into UTC too. You could use QString to std::string for the string stream. And do the following:
> 
> std::tm tm = {};
> std::stringstream ss("Jan 9 2014 12:35:34"); // Change this for the QDateTime toString().toStdString()
> ss >> std::get_time(&tm, "%b %d %Y %H:%M:%S");
> auto tp = std::chrono::system_clock::from_time_t(std::mktime(&tm));
> 
> I don't think it's the best solution, but could work easily if performance is not an issue. Hope someone have a better plan...

This is a tad overkill, you can use QDateTime::toMSecsSinceEpoch(), 
divide by 1000 and build a std::time_t out of it. (Remember to check for 
overflows, as you don't know what type std::time_t actually is.)

But also, why going down this route? Can't you simply build a 
std::chrono::system_clock::time_point out of a duration? I.e. 
(pseudocode, not tested):

> QDateTime dt;
> std::chrono::milliseconds duration{dt.toMSecsSinceEpoch()};
> std::chrono::system_clock::time_point tp{duration};

Last, but not least, note that std::system_clock is a Unix clock only 
starting in C++2a; before you had no guarantees. Does anyone know if 
QDateTime::toMSecsSinceEpoch() returns UTC time or Unix time?


Cheers,
-- 
Giuseppe D'Angelo | giuseppe.dangelo at kdab.com | Senior Software Engineer
KDAB (France) S.A.S., a KDAB Group company
Tel. France +33 (0)4 90 84 08 53, http://www.kdab.com
KDAB - The Qt, C++ and OpenGL Experts

-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/pkcs7-signature
Size: 4007 bytes
Desc: Firma crittografica S/MIME
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20181102/aeb88112/attachment.bin>


More information about the Interest mailing list