Qt-时间

来源:互联网 发布:日本历史地震数据统计 编辑:程序博客网 时间:2024/05/22 04:32

- QDateTime

QDateTime dateTime;
QString dateTime_str = dateTime.currentDateTime().toString("yyyy-MM-dd hh:mm:ss");

// 从字符串转换为毫秒(需完整的年月日时分秒)
datetime.fromString("2011-09-10 12:07:50:541", "yyyy-MM-dd hh:mm:ss:zzz").toMSecsSinceEpoch();

// 从字符串转换为秒(需完整的年月日时分秒)
datetime.fromString("2011-09-10 12:07:50:541", "yyyy-MM-dd hh:mm:ss:zzz").toTime_t();

// 从毫秒转换到年月日时分秒
datetime.fromMSecsSinceEpoch(1315193829218).toString("yyyy-MM-dd hh:mm:ss:zzz");

// 从秒转换到年月日时分秒(若有zzz,则为000)
datetime.fromTime_t(1315193829).toString("yyyy-MM-dd hh:mm:ss[:zzz]");



- 获取系统时间

#include <QDateTime>
#include <QDebug>
...
QDateTime sysDateTime;
qDebug() <<sysDateTime.currentDateTime().toString("yyyy年MM月dd日 hh:mm:ss");



- 延时(4.7之前的版本不能使用)

#include <QApplication>
#include <QDateTime>
#include <QDebug>
...
qint64 startTime = QDateTime::currentMSecsSinceEpoch();
qDebug() << startTime;

while (1)
{
    if (QDateTime::currentMSecsSinceEpoch() - startTime > interval)  // interval为需要延时的时间(ms)
    {
        break;
    }

    QApplication::processEvents();  // 处理其他事件,避免程序出现假死
}

qDebug() << QDateTime::currentMSecsSinceEpoch();



- 计算2个操作的时间差

#include <QTime>
#include <QDebug>
...
QTime startTime = QTime::currentTime();
QTime endTime = QTime::currentTime();
qDebug() << startTime.msecsTo(endTime);    // 结果为ms
0 0
原创粉丝点击