2

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.

jxgn
  • 741
  • 2
  • 15
  • 36

2 Answers2

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});