Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Qt 在 Linux 環境下讀取與設定系統時間

環境:主機 Fedora 12,開發工具 Qt。

嵌入式裝置往往需要顯示與修改系統時間,下面示範如何用 QDateTime 讀取時間,並透過 date 指令把使用者輸入的時間寫回系統與硬體時鐘。

讀取系統時間

[cpp]
void moreidDialog::refresh_time()
{
    QDateTime time;
    txt_time->setText(time.currentDateTime().toString("yyyy") + "." +
                      time.currentDateTime().toString("M")    + "." +
                      time.currentDateTime().toString("d")    + "." +
                      time.currentDateTime().toString("h")    + "." +
                      time.currentDateTime().toString("m"));
}

只讀到「分」,各段之間以「.」分隔,最終顯示效果例如:2011.12.27.9.14。

設定系統時間

[cpp]
// 儲存時間鍵
void moreidDialog::slot_save_time_key()
{
    QDateTime time;
    QString str = txt_time->text();

    // 先檢查格式是否正確:應該有 4 個小數點
    if (str.count(".") != 4)
    {
        txt_time->setText(tr("ge shi cuo wu"));
        return;
    }

    int i = 0, j = 0;
    i = str.indexOf(".");
    QString year  = str.mid(0, i);
    j = str.indexOf(".", i + 1);
    QString month = str.mid(i + 1, j - i - 1);
    i = j;
    j = str.indexOf(".", i + 1);
    QString day   = str.mid(i + 1, j - i - 1);
    i = j;
    j = str.indexOf(".", i + 1);
    QString hour  = str.mid(i + 1, j - i - 1);
    i = j;
    j = str.indexOf(".", i + 1);
    QString min   = str.mid(i + 1, j - i - 1);

    bool ok = false;
    year.toInt(&ok);
    if (ok == false) { txt_time->setText(tr("ge shi cuo wu")); return; }
    month.toInt(&ok);
    if (ok == false) { txt_time->setText(tr("ge shi cuo wu")); return; }
    day.toInt(&ok);
    if (ok == false) { txt_time->setText(tr("ge shi cuo wu")); return; }
    hour.toInt(&ok);
    if (ok == false) { txt_time->setText(tr("ge shi cuo wu")); return; }
    min.toInt(&ok);
    if (ok == false) { txt_time->setText(tr("ge shi cuo wu")); return; }

    // 設定日期
    str = "date -s " + month + "/" + day + "/" + year;
    system(str.toLatin1().data());
    // 設定時間
    str = "date -s " + hour + ":" + min + ":" + "00";
    system(str.toLatin1().data());
    // 強制寫入 CMOS
    system("clock -w");
}

補充:兩種時鐘的同步指令

硬體時鐘同步到系統時鐘:hwclock --hctosys
系統時鐘同步到硬體時鐘:hwclock -systohc

Linux 的系統時間與 RTC 硬體時鐘是各自獨立的,因此改完系統時間後要呼叫 clock -w(等同 hwclock -systohc)寫回硬體,重新開機才不會又跑掉。另外,date -s 需要 root 權限,若程式以一般使用者執行,記得在啟動時給予適當的權限設定。

Copyright © Linux教程網 All Rights Reserved