Nominate our 2022 Qt Champions!

Parse Date/Time with timezone offset and convert to local date / time String

  • Hi,

    i would like to parse the following String "2020-10-14T21:22:24+02:00" to a QDateTime Object for the Timezone "Europe/Berlin" (or the Timezone of the Phone). The question how can i do this. I always seem to get the wrong local time. With Java (my primary language) this works fine and i get the expected result (-> "14.22.2020 21:10:24") :

    ZonedDateTime zdt = ZonedDateTime.parse("2020-10-14T21:22:24+02:00"); ZoneId swissZone = ZoneId.of("Europe/Berlin"); ZonedDateTime germanDate = zdt.withZoneSameInstant(swissZone); LocalDateTime german = germanDate.toLocalDateTime();

    However with Qt/CCP i do not get the same result - the offset always seems to be added
    to the given time, not respecting my timezone:

    QDateTime utcDateTime = QDateTime::fromString(utcDateTimeString, Qt::ISODate); QDateTime localDateTime = QDateTime(, utcDateTime.time(), Qt::UTC).toLocalTime();
    => "2020-10-15 00:22:24"

    Any ideas how to parse the string so i can finally format the date/time string for the request (Berlin) locale?

  • Your string have "+02:00" in it so it is not an UTC time.

    //This is not Qt::UTC but Qt::OffsetFromUTC because of the "+02:00"
    QDateTime::fromString("2020-10-14T21:22:24+02:00", Qt::ISODate);

    If you want an UTC time

    QDateTime utcDateTime = QDateTime::fromString(utcDateTimeString, Qt::ISODate).toUTC();

    I'm not familiar with toLocalDateTime() in java, but I think toLocalTime() might be not quite the same with it.
    It will convert the datetime to your system's locale time.
    Anyway if you want to convert it to Timezone "Europe/Berlin".

    QDateTime localDateTime = utcDateTime.toTimeZone(QTimeZone("Europe/Berlin"));

    As I tested, you'll get "2020-10-14 21:22:24" for "Europe/Berlin" time, the same as "+02:00", because of the DST.
    If you change the month to November

    QString dateTimeString = "2020-11-14T21:22:24+02:00";
    QDateTime berlinDateTime = QDateTime::fromString(dateTimeString , Qt::ISODate).toTimeZone(QTimeZone("Europe/Berlin"));

    Then you'll get "2020-11-14 20:22:24"

Log in to reply