首页 > 技术知识 > 正文

Qt获取当前时间

时间日期是经常遇到的数据类型,Qt 中时间日期类型的类如下: QTime:时间数据类型,仅表示时间,如12:12:13。 QDate:日期数据类型,仅表示日期,如2020-11-21。 QDateTime:日期时间数据类型,表示日期和时间,如2020-11-22 12:12:13。

使用QDateTime类(毫秒精度)

QDateTime current_date_time = QDateTime::currentDateTime(); QString current_date = current_date_time.toString(“yyyy-MM-dd hh:mm::ss.zzz”); current_date字符串结果为”2020-11-21 12:17:01.445 “,其中时间的显示格式可灵活配置,此处简单说明本实例中用到的部分: Qt获取当前时间 在设置日期时间显示字符串格式时,还可以使用填字符,甚至使用汉字。例如,日期显示格式可以设置为: curDateTime.toString (“yyyy 年 MM 月 dd 日”);

只需要时间,不需要日期,也可使用QTime类

QTime current_time =QTime::currentTime(); int hour = current_time.hour();//当前的小时 int minute = current_time.minute();//当前的分 int second = current_time.second();//当前的秒

使用GetLocalTime函数(毫秒精度)

SYSTEMTIME sys; GetLocalTime(&sys); qDebug() << sys.wYear << sys.wMonth << sys.wDay << sys.wHour << sys.wMinute << sys.wSecond << sys.wMilliseconds

时间戳转换 时间转时间戳:

QDateTime time = QDateTime::currentDateTime(); //获取当前时间

int timeT = time.toTime_t(); //将当前时间转为时间戳 时间戳转时间:

QDateTime time = QDateTime::fromTime_t(timeT); 时间戳解释: 时间戳是指格林威治时bai间1970年01月01日00时00分00秒du(北京zhi时间1970年01月01日08时00分00秒)起至现在的总秒数。通俗的讲dao, 时间戳是一份能够表示一份数据在一个特定时间点已经存在的完整的可验证的数据。

字符串转时间

QString timeStr= “2019-03-31 12:24:36”; QDateTime time = QDateTime::fromString(timeStr, “yyyy-MM-dd hh:mm:ss”);

猜你喜欢