【问题标题】:Get local time in seconds using Qt使用 Qt 以秒为单位获取本地时间
【发布时间】:2016-08-03 01:09:56
【问题描述】:

我被这个问题困住了。

我已经在几秒钟内从QDateTime 获得了currentUTCtime。 问题是,我找不到以秒为单位将其转换为本地时间的可能方法。有一些像toLocalTime() 这样的QDate 函数似乎不起作用。我希望这里有人可以帮助我。

QDateTime::currentMSecsSinceEpoch();
QDateTime currentateTime = QDateTime::currentDateTime();
QDateTime UTC(QDateTime::currentDateTimeUtc());
currentDateTime.toString().toStdString();
TimeNow = currentDateTime.toMSecsSinceEpoch()/1000;

以上是我当前UTC时间的代码,以秒为单位。

【问题讨论】:

    标签: qt utc localtime qdatetime


    【解决方案1】:

    如果您只需要自纪元以来的秒数,您可以使用QDateTime::toTime_t();这种方法存在于 Qt 4.7 中,并且似乎从一开始也是 Qt 5 的一部分。

    QDateTime::currentDateTime().toTime_t()
    

    本地时间,或 UTC

    QDateTime::currentDateTimeUtc().toTime_t()
    

    【讨论】:

      【解决方案2】:

      使用QDateTime::fromTime_t,文档指出:

      返回一个日期时间,其日期和时间是自 1970-01-01T00:00:00、协调世界时 (Qt::UTC) 以来经过的秒数并转换为给定规范.

      qint64 utcTime = QDateTime::currentMSecsSinceEpoch();
      QDateTime localTime = QDateTime::fromTime_t(utcTime, Qt::LocalTime);
      

      【讨论】:

      • 啊,这个不错。谢谢!现在的问题是有一个错误说:没有匹配函数调用 'QDateTime::fromTime_t(qint64&, Qt::TimeSpec)' 我错过了什么吗?
      • 您必须至少使用 Qt 5.2
      • 哦,这将是问题所在。在这一点上这是无法实现的。有没有其他方法可以做到这一点?谢谢
      • Qt 4.8 有QDateTime::toTimeSpec 可能有用。
      猜你喜欢
      • 2017-08-05
      • 2012-10-07
      • 2022-07-07
      • 2011-04-30
      • 1970-01-01
      • 2014-08-24
      • 1970-01-01
      • 2015-10-14
      • 2017-11-29
      相关资源
      最近更新 更多