How to change system time of a linux device with Qt?

255 Views Asked by At

Im currently designing an user interface which requires to display the current date and time and also let the user edit the current time and date later in the settings.

I have been reading a lot about this issue today but i couldnt find a solution that worked for me. I tried to solve the issue with the QProcess by creating an QProcess object and executing the commands on the linux device my user interface is for. I just seem to struggle with the "date" command when i try to set the time.

This is my current code to change the system time of my linux device with the "date" command.

My issue is that if i run my programm with the "args << ...." line commented it shows me the StdOut of the current system time. BUT if i run the code with the args and try to set time i always get the same error message StdError "date: invalid date '"Mon Jan 23 09:30:17 UTC 2023"' for every possible format. i have tried many different formats and variations how you can set the time but i always get the same error message.

    QProcess task;
    QString command;
    QStringList args;

    command = "date";
    // I tried many different time formats but all of seem to be invalid

    args << "--set=\"Mon Jan 23 09:30:17 UTC 2023\"";
    task.start(command, args);
    task.waitForFinished();

    QString StdOut = task.readAllStandardOutput();
    QString StdError = task.readAllStandardError();

    ui->lineEdit_13->setText(StdOut);
    ui->lineEdit_14->setText(StdError);

Does anyone know what might be my problem and how to fix it? I surely cant be that hard to change the time of a device.

Thanks in advance for the answers :)

2

There are 2 best solutions below

0
Pamputt On

Could you try:

args << QStringLiteral("-s")
     << QStringLiteral("Mon Jan 23 09:30:17 UTC 2023");

You have an issue with the quotes.

Also, please note that you need to run your app with enough access privileges to modify the system date.

1
TerminusEst On

Sooo i found a very very easy method to change the system time of my display im using for my application. I read many times that changing system time wasnt possible with pure Qt but that is a very big lie.

You dont need QProcess at all. Just watch out that this applies for linux devices only

I used the dateTimeWidget. I just put it next my visible area of my application so i can access its functions.

So to change system time in Qt i used following line of code

ui->dateTimeWidget->setCTime(jahr_val,monat_val, tag_val, stunde_val, minute_val, sekunde_val, true);

Last argument needs to be true to sync the time you just set with the system clock. Easy as that.

Edit:

In the Image you can see the Widget I used. I couldnt find it in any documentation so it could be exclusive to the version i use idk I found it under help in the Widget Library Documentation

DateTimeWidget on the left in Qt Creator