在 Qt 中,可以使用 QDateTime
、QDate
或 QTime
类的 toString()
方法进行时间格式化输出。以下是详细说明和示例:
1. 基本格式化
使用预定义的格式字符串或自定义格式说明符:
常用格式说明符:
- 日期:
yyyy
:四位年份(如 2023)MM
:两位月份(01-12)dd
:两位日期(01-31)MMM
:缩写月份(如 Jan)MMMM
:完整月份(如 January)
- 时间:
HH
:24小时制小时(00-23)hh
:12小时制小时(01-12)mm
:分钟(00-59)ss
:秒(00-59)zzz
:毫秒(000-999)AP
/A
:上午/下午(AM/PM 或本地化文本)
2. 示例代码
获取当前时间并格式化:
QDateTime now = QDateTime::currentDateTime();
// ISO 8601 格式(如 2023-10-05T14:30:45)
QString isoFormat = now.toString(Qt::ISODate);
// 自定义格式(如 2023-10-05 14:30:45)
QString customFormat = now.toString("yyyy-MM-dd HH:mm:ss");
// 12小时制(如 2023-10-05 02:30:45 PM)
QString twelveHourFormat = now.toString("yyyy-MM-dd hh:mm:ss AP");
仅日期或时间:
QDate date = QDate::currentDate();
QTime time = QTime::currentTime();
QString dateStr = date.toString("yyyy-MM-dd"); // 如 2023-10-05
QString timeStr = time.toString("HH:mm:ss.zzz"); // 如 14:30:45.678
3. 本地化输出
使用 QLocale
结合区域设置:
QLocale locale(QLocale::Chinese); // 中文环境
QDateTime now = QDateTime::currentDateTime();
// 中文日期时间(如 2023年10月5日 下午02时30分45秒)
QString localizedStr = locale.toString(now, "yyyy'年'M'月'd'日' Ah时m分s秒");
4. 完整示例
#include <QDateTime>
#include <QDebug>
int main() {
QDateTime now = QDateTime::currentDateTime();
// 标准格式
qDebug() << "ISO Date:" << now.toString(Qt::ISODate);
// 自定义格式
qDebug() << "Custom Format:" << now.toString("yyyy-MM-dd HH:mm:ss.zzz");
// 12小时制 + 本地化
qDebug() << "12-hour Format:" << now.toString("hh:mm:ss AP");
// 中文本地化
QLocale locale(QLocale::Chinese);
qDebug() << "Chinese Format:" << locale.toString(now, "yyyy'年'MM'月'dd'日'");
return 0;
}
输出示例:
ISO Date: "2023-10-05T14:30:45"
Custom Format: "2023-10-05 14:30:45.678"
12-hour Format: "02:30:45 PM"
Chinese Format: "2023年10月05日"
注意事项:
- 区域设置:
AP/A
的输出依赖系统区域设置(如中文系统可能显示“上午/下午”)。 - 转义字符:使用单引号
'
包裹固定文本(如yyyy'年'MM'月'
)。 - 性能:频繁格式化时,可预生成
QLocale
对象以避免重复创建开销。