QT 实现时间的获取

1. 根据时区获取时间

#include <QCoreApplication>
#include <QDateTime>
#include <QTimeZone>
#include <QDebug>

int main(int argc, char *argv[]) {
    QCoreApplication app(argc, argv);

    QTimeZone timeZone("Europe/Paris");
    QDateTime dateTime = QDateTime::currentDateTime().toTimeZone(timeZone);
    qDebug() << "Current time in Paris:" << dateTime.toString();

    return app.exec();
}

2. 将时间转为时间戳,设置硬件时间

#include <QDateTime>
#include <QDebug>

int main() {
    // 创建一个 QDateTime 对象,设定一个特定的日期和时间
    QDateTime dateTime(QDate(2024, 4, 18), QTime(12, 30, 0));  // 2024年4月18日 12:30:00

    // 转换为时间戳(秒)
    qint64 timestamp = dateTime.toSecsSinceEpoch();

    qDebug() << "Unix timestamp in seconds:" << timestamp;

    return 0;
}

3. 将时间戳转为正常时间

        并设置硬件时间

#include <QCoreApplication>
#include <QDBusConnection>
#include <QDBusMessage>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    // 连接到系统的session bus
    QDBusConnection bus = QDBusConnection::systemBus();

    if (!bus.isConnected()) {
        qWarning() << "Failed to connect to system bus.";
        return 1;
    }

    // 设置要调用的接口和方法
    QString service = "org.freedesktop.timedate1";
    QString path = "/org/freedesktop/timedate1";
    QString iface = "org.freedesktop.timedate1";
    QString method = "SetTime";

    // 获取当前系统时间作为参数
    QDateTime currentDateTime = QDateTime::currentDateTime();
    qlonglong timestamp = currentDateTime.toSecsSinceEpoch() * 1000000; // 转换为微秒

    // 构造DBus消息
    QDBusMessage message = QDBusMessage::createMethodCall(service, path, iface, method);
    message << timestamp << true; // 参数为时间戳和是否UTC时间

    // 调用DBus接口
    QDBusMessage reply = bus.call(message);

    if (reply.type() == QDBusMessage::ReplyMessage) {
        qDebug() << "Hardware time set successfully.";
    } else {
        qWarning() << "Failed to set hardware time:" << reply.errorMessage();
    }

    return app.exec();
}

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值