Can someone show me how to set time zone in Qt? Currently I am using the linux system() call to set the time zone, but this is not reflecting in currentTime() API of Qt. There is a setTimeZone() API in Qt 5 and above but I have no idea how to use it. Thanks in advance.
Asked
Active
Viewed 5,275 times
2
-
I don't understand what you want to achieve. Do you want to display times in the system timezone, or do you want to actually change the timezone of the system? – Frank Osterfeld May 01 '15 at 11:24
-
change the timezone of the system itself. – jxgn May 01 '15 at 11:34
-
There's no API for that in Qt. That's system configuration, usually nothing a normal application is (or should be) concerned with. – Frank Osterfeld May 01 '15 at 13:09
-
what about the QDateTine::setTimeZone() API? What does it do? – jxgn May 01 '15 at 17:38
-
1It's sets the timezone for that particular QDateTime object, representing a date and time. It has nothing to do with the system timezone. – Frank Osterfeld May 01 '15 at 17:44
-
Thanks. Can you show me an example? – jxgn May 02 '15 at 05:24
2 Answers
1
As stated by Frank in the comments, there is no API in Qt to directly change the system timezone. Using timedatectl
is one way to go.
However instead of a system()
call, QProcess
could be used like this for an example timezone:
auto timezone = QString("Europe/Paris");
auto command = QString("timedatectl set-timezone ") + timezone;
auto ret = QProcess::execute(command);
if (ret != 0) {
qDebug("timedatectl failed : %d", ret);
}
If there is already a QTimeZone object in use, the command can be assembled like this:
auto timezoneObj = QTimeZone();
// process timezoneObj
if (!timezoneObj.isValid()) {
qDebug("invalid timezone qobject");
return;
}
auto timezone = timezoneObj.id();
auto command = QString("timedatectl set-timezone ") + timezone;
auto ret = QProcess::execute(command);
if (ret != 0) {
qDebug("timedatectl failed : %d", ret);
}

bunto1
- 331
- 4
- 15
1
Instead of using QProcess I'd probably recommend to use QDBus instead.
qdbus command line call:
qdbus --system org.freedesktop.timedate1 /org/freedesktop/timedate1 org.freedesktop.timedate1.SetTimezone Europe/Berlin false
Qt code:
QDBusInterface timedated("org.freedesktop.timedate1", "/org/freedesktop/timedate1", "org.freedesktop.timedate1", QDBusConnection::systemBus());
QDBusPendingReply<> setTz = timedated.callWithArgumentList(QDBus::Block, "SetTimeZone", {"Europe/Berlin", false});

Michael Zanetti
- 71
- 3