ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[TOC] ## 概述 处理日期和时间的函数 ## 示例 ### 当前时间和日期 ``` QDateTime currentDateTime = QDateTime::currentDateTime(); qDebug() << "Current Date and Time:" << currentDateTime.toString("yyyy-MM-dd hh:mm:ss"); ``` ### 根据日期和时间 ``` QDate date(2023, 9, 8); QTime time(14, 30); QDateTime customDateTime(date, time); qDebug() << "Custom Date and Time:" << customDateTime.toString("yyyy-MM-dd hh:mm:ss"); ``` ### 计算日期差距 ``` QDate date1(2023, 9, 1); QDate date2(2023, 9, 8); int daysBetween = date1.daysTo(date2); qDebug() << "Days between date1 and date2:" << daysBetween; ``` ### 添加时间间隔 ``` QDateTime dateTime(2023, 9, 8, 14, 30); QTimeSpan timeSpan(2, 30); // 2小时30分钟 dateTime = dateTime.addSecs(timeSpan.totalMilliseconds() / 1000); qDebug() << "New Date and Time:" << dateTime.toString("yyyy-MM-dd hh:mm:ss"); ``` ### 比较日期和时间 ``` QDateTime dateTime1(2023, 9, 8, 10, 0); QDateTime dateTime2(2023, 9, 8, 14, 30); if (dateTime1 < dateTime2) { qDebug() << "dateTime1 is before dateTime2."; } else { qDebug() << "dateTime1 is after or equal to dateTime2."; } ``` ### 解析日期和时间字符串 ``` QString dateTimeString = "2023-09-08 14:30:00"; QDateTime parsedDateTime = QDateTime::fromString(dateTimeString, "yyyy-MM-dd hh:mm:ss"); qDebug() << "Parsed Date and Time:" << parsedDateTime.toString("yyyy-MM-dd hh:mm:ss"); ``` ### 获取日期和时间的各个部分 ``` QDateTime dateTime = QDateTime::currentDateTime(); int year = dateTime.date().year(); int month = dateTime.date().month(); int day = dateTime.date().day(); int hour = dateTime.time().hour(); int minute = dateTime.time().minute(); int second = dateTime.time().second(); qDebug() << "Year:" << year << "Month:" << month << "Day:" << day << "Hour:" << hour << "Minute:" << minute << "Second:" << second; ```