Qt Forum

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Unsolved

    Solved QDateTime::toMSecsSinceEpoch() always treats my time as local. Can't get toTimeSpec() to work

    General and Desktop
    2
    3
    193
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • Y
      yuanqufucius last edited by

      I want milliseconds since epoch from a time string.
      I understand the epoch is time since midnight 1970-Jan-01 in UTC.

      With:

      return QDateTime::fromString("2020-01-28 00:00:00", "yyyy-MM-dd 00:00:00").toMSecsSinceEpoch()
      

      I get 1580191200000, which is 2020-01-28 06:00:00. This would make sense if QDateTime::fromString() defaults to my system's local time. Since I am in UTC-6 time zone.

      But even if I set the timespec to UTC, as in I am telling QT that the time given "2020-01-28 00:00:00" is in UTC

      return QDateTime::fromString("2020-01-28 00:00:00", "yyyy-MM-dd 00:00:00").toTimeSpec(Qt::UTC).toMSecsSinceEpoch()
      

      I still get 1580191200000. Is it a bug or how am I doint this wrong?

      Thanks!

      KroMignon 1 Reply Last reply Reply Quote 0
      • KroMignon
        KroMignon @yuanqufucius last edited by

        @yuanqufucius said in QDateTime::toMSecsSinceEpoch() always treats my time as local. Can't get toTimeSpec() to work:

        return QDateTime::fromString("2020-01-28 00:00:00", "yyyy-MM-dd 00:00:00").toTimeSpec(Qt::UTC).toMSecsSinceEpoch()

        Hello and welcome to Qt Forum, toTimeSpec() is not the right method, you should use setTimeSpec().

        return QDateTime::fromString("2020-01-28 00:00:00", "yyyy-MM-dd 00:00:00").setTimeSpec(Qt::UTC).toMSecsSinceEpoch();
        

        QDateTime::toTimeSpec() will create a new QDateTime at same epoch time but with another time zone.
        QDateTime::setTimeSpec() will change the time zone of the QDateTime instance.

        It is an old maxim of mine that when you have excluded the impossible, whatever remains, however improbable, must be the truth. (Sherlock Holmes)

        1 Reply Last reply Reply Quote 4
        • Y
          yuanqufucius last edited by

          Thanks! That would make sense.

          1 Reply Last reply Reply Quote 1
          • First post
            Last post