55

I'm trying to get the current time as TimeStamp without success.

I have this code:

QDateTime setTime = QDateTime::fromString (QString("1970-07-18T14:15:09"), Qt::ISODate);
QDateTime current = QDateTime::currentDateTime();
uint msecs = setTime.time().msecsTo(current.time());

return  QString::number(msecs);

The output is

Sunday, January 25th 1970, 03:17:35 (GMT)
1
  • What exactly do you mean by timestamp? Please provide expected output.
    – chalup
    May 6, 2010 at 13:11

3 Answers 3

92

In Qt 4.7, there is the QDateTime::currentMSecsSinceEpoch() static function, which does exactly what you need, without any intermediary steps. Hence I'd recommend that for projects using Qt 4.7 or newer.

5
  • 11
    Be aware that this returns the interval in miliseconds and not seconds. So it is not unix time!
    – drzymala
    Jun 4, 2013 at 14:07
  • 2
    Simply do (QDateTime::currentMSecsSinceEpoch() / 1000) which should make it Unix time :P Mar 7, 2016 at 12:51
  • This answer causes me to wasting time! because this is not exactly unix time as @martini mentioned. Apr 28, 2016 at 2:02
  • 6
    In qt 5.8 (at the time of writing brand new) they have added the currentSecsSinceEpoch function: doc.qt.io/qt-5/qdatetime.html#currentSecsSinceEpoch
    – sunyata
    Jan 26, 2017 at 0:47
  • Works on PyQt 5.10 which I believe uses Qt 5.10 Nov 14, 2018 at 5:06
39

I think you are looking for this function:

http://doc.qt.io/qt-5/qdatetime.html#toTime_t

uint QDateTime::toTime_t () const

Returns the datetime as the number of seconds that have passed since 1970-01-01T00:00:00, > Coordinated Universal Time (Qt::UTC).

On systems that do not support time zones, this function will behave as if local time were Qt::UTC.

See also setTime_t().

3
  • 1
    i did that : QDateTime current = QDateTime::currentDateTime(); uint timestame = current.toTime_t(); ,but it didnt gave me the current date after i tested the result here : 4webhelp.net/us/timestamp.php
    – user63898
    May 6, 2010 at 13:30
  • 2
    just tried pass string returned by QDateTime::currentDateTime().toTime_t() to this site and got correct time. Maybe you set wrong timezone in the form on this site.
    – VestniK
    May 6, 2010 at 14:01
  • 1
    toTime_t() is deprecated, use toSecsSinceEpoch() instead (returns qint64 instead of 32-bit uint that overflows in 2106 year)
    – user
    Dec 10, 2019 at 20:28
11

Since Qt 5.8, we now have QDateTime::currentSecsSinceEpoch() to deliver the seconds directly, a.k.a. as real Unix timestamp. So, no need to divide the result by 1000 to get seconds anymore.

Credits: also posted as comment to this answer. However, I think it is easier to find if it is a separate answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.