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.
-
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 OsterfeldCommented May 1, 2015 at 11:24
-
change the timezone of the system itself.– jxgnCommented May 1, 2015 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 OsterfeldCommented May 1, 2015 at 13:09
-
what about the QDateTine::setTimeZone() API? What does it do?– jxgnCommented May 1, 2015 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 OsterfeldCommented May 1, 2015 at 17:44
|
Show 1 more comment
2 Answers
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);
}
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});