You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

QDateTime::toString(Qt::ISODateWithMs)未输出时区信息,是否为Bug?

QDateTime::toString(Qt::ISODateWithMs)未输出时区信息是否属于Bug?

我原本以为QDateTime::toString(Qt::ISODateWithMs)应该在字符串末尾输出“Z”或“±hh:mm”来标识时区信息,但运行以下代码后:

#include <QDateTime>
#include <QDebug>
int main(int argc, char *argv[])
{
    QDateTime now = QDateTime::currentDateTime();
    qDebug() << now;
    qDebug() << now.toString(Qt::ISODateWithMs);
    return 0;
}

得到的输出为:

QDateTime(2025-03-06 18:04:44.523 MSK Qt::LocalTime)
"2025-03-06T18:04:44.523"

结果未包含时区信息,仅输出本地时间。请问这是否属于Bug?

运行环境:

Operating System: Kubuntu 24.10
KDE Plasma Version: 6.1.5
KDE Frameworks Version: 6.6.0
Qt Version: 6.6.2

这不是Bug,是Qt的设计行为,原因如下:

  • QDateTime::currentDateTime()返回的是标记为Qt::LocalTime的本地时区时间对象,而Qt::ISODateWithMs的格式规则是:仅当QDateTime对象为UTC时区(Qt::UTC)或带有显式时区偏移时,才会在输出字符串末尾添加时区标识(Z或±hh:mm)。
  • 本地时区的时间可能受夏令时等因素影响,偏移并非固定值,因此Qt默认不会为本地时区的QDateTime附加时区信息。

如果需要输出带时区标识的ISO格式时间,可采用以下两种方法:

  1. 转换为UTC时区后输出:
QDateTime now = QDateTime::currentDateTimeUtc();
qDebug() << now.toString(Qt::ISODateWithMs);
// 示例输出:"2025-03-06T15:04:44.523Z"
  1. 使用自定义格式字符串,显式指定时区偏移输出:
QDateTime now = QDateTime::currentDateTime();
qDebug() << now.toString("yyyy-MM-ddTHH:mm:ss.zzzXXX");
// 示例输出:"2025-03-06T18:04:44.523+03:00"

其中XXX格式符会输出当前时区的标准偏移,符合ISO 8601规范。


内容的提问来源于stack exchange,提问作者truf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 23:52:44