2010-05-06 97 views
37

我试图将当前时间作为TimeStamp而没有成功。如何获取当前TimeStamp?

我有这样的代码:

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); 

输出是

Sunday, January 25th 1970, 03:17:35 (GMT) 
+0

你是什么意思的时间戳?请提供预期产出。 – chalup 2010-05-06 13:11:55

+1

unix time == timestamp – user63898 2010-05-06 13:33:16

回答

34

我认为你正在寻找这样的功能:

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

UINT QDateTime :: toTime_t()const

将日期时间返回为自1970-01-01T00:00:00协调世界时(Qt :: UTC)以来传递的秒数。

在不支持时区的系统上,该函数的行为如同本地时间为Qt :: UTC。

另请参见setTime_t()。

+1

我做到了这一点:QDateTime current = QDateTime :: currentDateTime(); uint timestame = current.toTime_t(); ,但它没有给我当前的日期后,我在这里测试结果:http://www.4webhelp.net/us/timestamp.php – user63898 2010-05-06 13:30:47

+2

只是尝试传递字符串返回的QDateTime :: currentDateTime()。toTime_t()这个网站,并得到正确的时间。也许你在这个网站的表格中设置了错误的时区。 – VestniK 2010-05-06 14:01:05

+0

我也得到了正确的时间,使用相同的代码。 – Jack 2017-09-11 21:17:52

65

在Qt 4.7中,有一个静态函数QDateTime::currentMSecsSinceEpoch(),它完全符合您的需求,无需任何中间步骤。因此,我建议使用Qt 4.7或更新的项目。

+9

请注意,这将以**毫秒**而不是秒为单位返回间隔。所以这不是unix时间! – drzymala 2013-06-04 14:07:29

+2

简单地做(QDateTime :: currentMSecsSinceEpoch()/ 1000)应该使它成为Unix时间:P – 2016-03-07 12:51:31

+0

这个答案使我浪费时间!因为@martini提到这并不完全是unix时间。 – 2016-04-28 02:02:53