Qt QDateTime从字符串与时区和夏时制

时间:2019-03-27 05:57:12

标签: c++ qt timezone dst

我正在从字符串中插入时间

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

我得到的输出

  • “ 2019年3月26日星期二23:37:40”
  • “格林尼治标准时间2019年3月27日星期三06:37:40”
  • false

应该给的

  • “ 2019年3月26日星期二23:37:40”
  • “格林尼治标准时间2019年3月27日星期三05:37:40”
  • true

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

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分:2)

首先,根据“ 2019年3月26日星期三22:37:40 GMT-08”计算得出的UTC时间“ 2019年3月27日星期三GMT”绝对正确。您如何看待5:37?

为什么GMT或UTC不包含DST:

  

夏时制(DST)的UTC和GMT都不会更改。   但是,某些使用格林尼治标准时间的国家/地区切换到了不同的时间   夏令时期间的区域。例如,AKDT(阿拉斯加日光   时间)是夏令时(夏令时)的GMT-8时区之一   节省时间)在2019年3月10日至11月3日之间。   冬天,正在使用GMT-9的AKST(阿拉斯加标准时间)。

第二,正如其他回答时间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