Qt QDateTime 纳秒(1970 年 1 月 1 日起)
我即将从一个文件中读取数据,该文件存储了 1970 年 1 月 1 日起的纳秒时间。我的问题是我想将其读取到 QDateTime 对象,但它根本无法按照我想要的方式工作,并且 Qt 文档也没有帮助我。
注意:毫秒光栅足以满足我的目的 这是我目前的方法:
void setDateTime(qint64 &ns)
{
_datetime.setDate(QDate(1970,1,1));
_datetime.setTime(QTime(0,0,0,0));
ns /= 1000; //ns are now ms
qDebug() << "| ms = " << ns;
qDebug() << "| days = " << static_cast<int>(ns%(60*60*24*1E6));
_datetime.addDays( static_cast<int>(ns%(60*60*24*1000)) );
_datetime.addMSecs( ns - ((ns/(60*60*24*1000))*60*60*24*1E6) );
qDebug() << "| dt = " << _datetime;
}
结果总是
| dt = QDateTime("Thu Jan 1 00:00:00 1970")
肯定是错误的,
有人能告诉我我的缺陷在哪里吗?感谢您的任何提示和帮助。
编辑: setTime_t 显然是我想要的(除了毫秒分辨率),并且按预期工作,但我真的很好奇为什么上述方法不起作用。
编辑将 hack-away 错误从 1E6 乘法更改为 1E6
I am about to read data From a File which has stored it's time in nanoseconds from 1/1/1970. My problem is I want to read it to a QDateTime
object, but it simply does not work as I want it to and the Qt Documentation did not help me either.
Note: milliseconds raster is enough for my purposes
Here my current approach:
void setDateTime(qint64 &ns)
{
_datetime.setDate(QDate(1970,1,1));
_datetime.setTime(QTime(0,0,0,0));
ns /= 1000; //ns are now ms
qDebug() << "| ms = " << ns;
qDebug() << "| days = " << static_cast<int>(ns%(60*60*24*1E6));
_datetime.addDays( static_cast<int>(ns%(60*60*24*1000)) );
_datetime.addMSecs( ns - ((ns/(60*60*24*1000))*60*60*24*1E6) );
qDebug() << "| dt = " << _datetime;
}
the result is always
| dt = QDateTime("Thu Jan 1 00:00:00 1970")
which is surely wrong
Can anybody tell where my flaw is? Thanks for any tips and help.
Edit: setTime_t is obviously what I wanted (except for msec resolution), and that works as expected, but I am really curious why the above approach does not work.
Edit changed hack-away bug from 1E6 multiplicative to 1E6
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
QDateTime::addDays()
和QDateTime::addMSecs()
是返回新QDateTime
的 const 函数。你只是把返回值扔掉了。是的,这是写在文档中的。
QDateTime::addDays()
andQDateTime::addMSecs()
are const functions returning a newQDateTime
. You're simply throwning the return value away.And yes, this is written in the documentation.