QDateTime::toMSecsSinceEpoch() always treats my time as local. Can't get toTimeSpec() to work
-
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!
-
@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 usesetTimeSpec()
.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. -
Thanks! That would make sense.