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.

6
  • 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? Commented May 1, 2015 at 11:24
  • change the timezone of the system itself.
    – jxgn
    Commented 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. Commented May 1, 2015 at 13:09
  • what about the QDateTine::setTimeZone() API? What does it do?
    – jxgn
    Commented May 1, 2015 at 17:38
  • 1
    It's sets the timezone for that particular QDateTime object, representing a date and time. It has nothing to do with the system timezone. Commented May 1, 2015 at 17:44

2 Answers 2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.