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

Qt::ISODate格式下QDateTime::fromString返回错误值如何解决

问题原因

你遇到的解析错误是Qt 5版本QDateTime::fromString接口的特性导致,核心有两个问题:

  • Qt::ISODate枚举在Qt 5的实现中不支持带Z后缀的UTC标记ISO8601字符串,仅能解析无时区后缀的标准时间格式
  • 自定义格式字符串中的Z是Qt的保留占位符,用于匹配时区偏移值,不能直接匹配字符串中的字面量Z,需要转义处理

解决方法

方案1:使用兼容时区的ISO格式枚举(Qt 5.8及以上版本适用)

Qt 5.8新增的Qt::ISODateWithMs枚举同时支持带Z后缀、带毫秒的ISO8601格式,直接替换原有格式参数即可:

QString aString          = "2021-09-10T15:56:00Z";
QString aDifferentString = "2021-09-10T15:56:00";
QString theString = durationInfo.value("end").toString();

// 同时兼容带Z和不带Z的ISO8601时间解析
QDateTime aDateTime = QDateTime::fromString(aString, Qt::ISODateWithMs);
QDateTime aDifferentDateTime = QDateTime::fromString(aDifferentString, Qt::ISODateWithMs);
endTime = QDateTime::fromString(theString,Qt::ISODateWithMs);

方案2:使用转义后的自定义格式

如果需要手动指定格式字符串,需要把字面量Z用单引号包裹转义,解析后手动标记为UTC时区即可:

// 转义Z为普通字符匹配
QDateTime anotherDateTime = QDateTime::fromString(aString, "yyyy-MM-ddTHH:mm:ss'Z'");
// 手动设置为UTC时区,避免被识别为本地时间
anotherDateTime.setTimeSpec(Qt::UTC);

上述两种方案在Qt 5.15 MSVC 2019环境下均可正确解析出对应时间,不会返回1970年代的无效值。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 12:45:04