Search code examples
c++qtmillisecondstime-format

A one line function to convert a hh:mm:ss.zzz time QString to milliseconds?


I'm using Qt and I have a time QString of format hh:mm:ss:zzz, such as 01:59:25.345. I am wondering if there is already some handy functions in Qt or c++ that can easily convert this to milliseconds. As to the QTime::fromMSecsSinceStartOfDay(12334).toString("hh:mm:ss.zzz"); for the other way around.


Solution

  • I think your format of Qt::ISODateWithMs is considered valid ISO 8601. Just prepend an aribitrary date with a T delimiter between date a and time.

    QString timestamp = "2020-01-01T01:59:25.345";
    int milliseconds = QDateTime::fromString(timestamp, Qt::ISODateWithMs).time().msecsSinceStartOfDay();
    

    Also, if the current day is a daylight savings start/end day, I'm not sure how that impacts the calculation, of it it even matters.