Qt to QML conversion: QDateTime -> date

3.5k Views Asked by At

So I'm sending a QDateTime to QML in order to display it and do some checkings (ideally I would like to be able to use all javascript date functions like getTime(),getMonth()...), and I realized if I send:

QDateTime(2019-10-30 11:15:00.000 CET Qt::TimeZone Europe/Amsterdam )

And then I read the date on QML, I get the time on the local timezone instead of the one set on the QDateTime...

Wed Oct 30 06:15:00 2019 GMT-0400 (NY timezone)

Is there any way I can keep the timezone in the QML side? Thanks!!

2

There are 2 best solutions below

0
On BEST ANSWER

Following the @Pedro's advice (I don't know how to tag you properly...), I used moment.js as well as moment-timezone.js so I could reference any date to the timezone I want. To anyone interested, that's how I did it:

import QtQuick 2.9
import "./moment.js" as Moment
import "./moment-timezone-with-data.js" as MomentTimezone

Item {
    anchors.fill: parent
    property date customDate: new Date(); // local timezone is "America/New_York"

    function getDateWithTimeZone(date, timeZone) {
        var momentDate = moment(new Date(date));
        var momentDateTz = momentDate.tz(timeZone);
        return momentDateTz;
    }

    Text {
        anchors.centerIn: parent
        text: customDate.toLocaleString() + "\n"
              + getDateWithTimeZone(customDate, "Europe/Paris").toString()
    }
}

which gives the following output:

enter image description here

1
On

The javascript Date class is quite limited. It holds an internal UTC time/date and doesn't allow to change the timezone. It also displays by default converting to the local timezone, which is what you have observed.

There is a javascript Moment library with timezone support, to alleviate some of the Date shortcomings, but it is not fully compatible with QML, IIRC.

Anyway, the best route seems to be avoiding Date objects in QML as much as you can, and use something else instead. Either a javascript alternative, or even better, your own C++ class encapsulating QDateTime, exposed as a context property to QML, with whatever methods you need in the QML side. Something like this example ApplicationData from the official Qt documentation.