Solved time zone other than UTC and local in QDateTimeEdit
-
I have a
QDateTimeEdit
in a form that I need to show times from time zones other than UTC and local. It's showing the time from an embedded device that might not be in the same time zone as the running form. Is there a way to do this? -
You can basically set any date and time you want with setDateTime
or with the constructor -
@koahnig I know that, but I can only seem to get it to display in UTC or machine's local time zone. I need a way to have the functionality of
QDateTimeEdit
plus have it display the time in a specified time zone. -
You need to show code snippet.
QDateTime allows you to retrieve through its static members currentDateTime the current local date and time and there is also the UTC variant. When you are using those static members for initialization of QDateTimeEdit you are certainly getting local respectively UTC.
However, you would need to initialize an instance of QDateTime with the value you like to use (e.g. using setDate or setTime.
-
@koahnig What I need is the editability of
QDateTimeEdit
, but have control over the time zone the widget displays in. -
What I discovered is that I needed to use
QDateTime::toTimeZone(const QTineZone&)
to convert the time and useQDateTimeEdit::setTimeSpec(Qt::TimeZone)
on the widget. -
To me, it looks like even though the solution from @kamorrissey got it to display with the correct time zone, the time that is returned is not correct.
dte is a QDateTimeEdit*, timezone is a valid QByteArray and I'm using 5.15.2.
auto time = QDateTime::currentDateTime(); dte->setDateTime(time.toTimeZone(QTimeZone(timezone))); dte->setTimeSpec(Qt::TimeZone); auto test = dte->dateTime().toSecsSinceEpoch() - time.toSecsSinceEpoch(); auto test2 = time.toTimeZone(QTimeZone(timezone)).toSecsSinceEpoch() - time.toSecsSinceEpoch();
I'm seeing that test returns -3600 (the difference between my local time and the timezone) and test2 returns 0 (as expected). I believe both should return 0.
-
@agarvey hi and welcome to devnet,
You need to provide more information about your timezone.
Showing all the different values you are using and getting would also help.
There's also the daylight saving time that might be at play at some point.
-
@agarvey said in time zone other than UTC and local in QDateTimeEdit:
timezone is a valid QByteArray
On my Ubuntu system
timezone
is (also) an external long int declared in time.h. Without declaring a QByteArray calledtimezone
this statement:dte->setDateTime(time.toTimeZone(QTimeZone(timezone)));
compiles happily here and becomes (in my UTC+10 TZ):
dte->setDateTime(time.toTimeZone(QTimeZone(-36000)));
which takes the time given to the date edit on a wild excursion.
Make sure of what you are actually getting.