Qt QDateTime来自字符串,带有时区和夏令时

问题描述 投票:1回答:2

我从字符串插入时间

QDateTime time =QDateTime::fromString("Wed Mar 26 22:37:40 2019 GMT-08");
qDebug()<<time.toLocalTime().toString();
qDebug()<<time.toUTC().toString();
qDebug()<<time.isDaylightTime();

输出我得到了

  • “星期二三月二十六日23:37:40 2019”
  • “Wed Mar 27 06:37:40 2019 GMT”

它应该给

  • “星期二三月二十六日23:37:40 2019”
  • “Wed Mar 27 05:37:40 2019 GMT”
  • 真正

如何通过时间戳字符串传递夏令时?

c++ qt timezone dst
2个回答
2
投票

如果您查看官方文档,它会说:

如果Qt :: TimeSpec不是Qt :: LocalTime或Qt :: TimeZone,那么将始终返回false。

首先,检查QDateTime::timeSpec是否正在返回您的预期。

如果您事先知道格式,请尝试使用等效函数QDateTime::fromString指定要解析的字符串的格式。

结合这两件事你可以做这样的事情:

const char* s = "2009-11-05T03:54:00";
QDateTime d = QDateTime::fromString(s, Qt::ISODate).toLocalTime();
d.setTimeSpec(Qt::LocalTime); // Just to ensure that the time spec are the proper one, i think is not needed
qDebug() << d.isDaylightTime();

2
投票

首先,UTC时间“Wed Mar 27 06:37:40 2019 GMT”绝对正确,从“Wed Mar 26 22:37:40 2019 GMT-08”计算。你觉得5:37怎么样?

解释为什么GMT或UTC不包含DST:

UTC和GMT都没有因夏令时(DST)而改变。但是,一些使用GMT的国家在夏令时期间会切换到不同的时区。例如,AKDT(阿拉斯加日光时间)是2019年3月10日至11月3日夏令时(夏季夏令时)期间的GMT-8时区之一。冬季,AKST(阿拉斯加标准时间),即GMT-9正在使用中。

第二,正如已经指出的另一个答案时间QDateTime::isDaylightTime always returns false if the Qt::TimeSpec is not Qt::LocalTime or Qt::TimeZone

当您在代码示例中使用带时区信息的QDateTime::fromString时,timespec被正确设置为Qt::OffsetFromUTC。您可以将另一个QDateTime对象同时实例化,但将TimeSpec作为Qt :: LocalTime或Qt :: TimeZone。你可以,例如使用QDateTime::toLocalTime转换为本地时间或使用QDateTime::fromSecsSinceEpoch转换为Qt :: LocalTime或Qt :: TimeZone,它接受时区的偏移秒数。

请参阅下面的示例代码我位于芬兰,夏令时在3月31日开始,所以当标准时间在使用时和使用白天时,您可以看到当地时间的差异:

QDateTime time = QDateTime::fromString("Wed Mar 26 22:37:40 2019 GMT-08");

qDebug()<<"\nLocal time EET:";
QDateTime localTime = time.toLocalTime();
// This works too, here to local time:
//QDateTime localTime = QDateTime::fromSecsSinceEpoch(time.toSecsSinceEpoch());
qDebug()<<localTime.timeSpec();
qDebug()<<localTime.timeZone();
qDebug()<<localTime.timeZoneAbbreviation();
qDebug()<<localTime.toLocalTime().toString();
qDebug()<<localTime.toUTC().toString();
qDebug()<<localTime.isDaylightTime();

time = QDateTime::fromString("Wed Apr 26 22:37:40 2019 GMT-08");

qDebug()<<"\nLocal time EEST:";
localTime = time.toLocalTime();
qDebug()<<localTime.timeSpec();
qDebug()<<localTime.timeZone();
qDebug()<<localTime.timeZoneAbbreviation();
qDebug()<<localTime.toLocalTime().toString();
qDebug()<<localTime.toUTC().toString();
qDebug()<<localTime.isDaylightTime();

输出:

Local time EET:
Qt::LocalTime
QTimeZone("Europe/Helsinki")
"EET"
"Wed Mar 27 08:37:40 2019"
"Wed Mar 27 06:37:40 2019 GMT"
false

Local time EEST:
Qt::LocalTime
QTimeZone("Europe/Helsinki")
"EEST"
"Sat Apr 27 09:37:40 2019"
"Sat Apr 27 06:37:40 2019 GMT"
true
© www.soinside.com 2019 - 2024. All rights reserved.