The QTime class provides clock time functions.
A QTime object contains a clock time, i.e. the number of hours, minutes, seconds, and milliseconds since midnight. It can read the current time from the system clock and measure a span of elapsed time. It provides functions for comparing times and for manipulating a time by adding a number of milliseconds.
QTime uses the 24-hour clock format; it has no concept of AM/PM. Unlike QDateTime, QTime knows nothing about time zones or daylight-saving time (DST).
A QTime object is typically created either by giving the number of hours, minutes, seconds, and milliseconds explicitly, or by using the static function currentTime(), which creates a QTime object that contains the system's local time. Note that the accuracy depends on the accuracy of the underlying operating system; not all systems provide 1-millisecond accuracy.
The hour(), minute(), second(), and msec() functions provide access to the number of hours, minutes, seconds, and milliseconds of the time. The same information is provided in textual format by the toString() function.
QTime provides a full set of operators to compare two QTime objects. QTime A is considered smaller than QTime B if A is earlier than B.
The addSecs() and addMSecs() functions provide the time a given number of seconds or milliseconds later than a given time. Correspondingly, the number of seconds or milliseconds between two times can be found using secsTo() or msecsTo().
QTime can be used to measure a span of elapsed time using the start(), restart(), and elapsed() functions.
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTime>
#include <QDebug>
#include <windows.h>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QTime time = QTime::currentTime();//获取当前事件
QString strTime = time.toString("hh:mm:ss.zzz");//转换成QString
time = QTime::fromString("02:23:45.789","hh:mm:ss.zzz");//QString转QTime
strTime = time.toString("hh:mm:ss.zzz");
QTime time1(7,30,5 ,100);//传递时分秒毫秒构造函数
strTime = time1.toString("hh:mm:ss.zzz");
int hour = time1.hour();//获取小时,7
qDebug()<<hour;
int minute=time1.minute();//获取分钟,30
qDebug()<<minute;
int second = time1.second();//获取秒数,5
qDebug()<<second;
int mssecond = time1.msec();//获取毫秒,100
qDebug()<<mssecond;
QTime t1 = time1.addMSecs(100);//增加100ms
qDebug()<<t1.msec();
QTime t2 = time1.addSecs(80);//增加80s
qDebug()<<t2.second();
if(time < time1)//比较两个QTime,时间晚的大
qDebug()<<"time<time1";
QTime t3;
t3.start();//开始计时
Sleep(1000);
int elspsed = t3.elapsed();//计算多少ms过去了
t3.restart();//重新计时
int milsecond = QTime::currentTime().msecsSinceStartOfDay();//返回从零点开始共计多少ms
qDebug()<<milsecond;
QTime t4(22,25,10);
QTime t5(22,24,0);
qDebug()<<t4.secsTo(t5);//两者相差了多少秒,t4到t5需要多少秒,如果t5<t4,返回负值
qDebug()<<strTime;
}
MainWindow::~MainWindow()
{
delete ui;
}
.