QT 实现时间的获取

  1. 根据时区获取时间
cpp 复制代码
#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();
}
  1. 将时间转为时间戳,设置硬件时间
cpp 复制代码
#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;
}
  1. 将时间戳转为正常时间

并设置硬件时间

cpp 复制代码
#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();
}
相关推荐
funnycoffee1234 小时前
linux系统DNS修改命令
linux·运维·服务器·linux dns
清漠2336 小时前
win11“网络和Internet“中无“以太网“这个选项解决记录
服务器·网络·数据库
袁小皮皮不皮6 小时前
数据通信20-IPv6基础
运维·服务器·网络·网络协议·智能路由器
醒醒该学习了!8 小时前
如何将json文件转成csv文件(python代码实操)
服务器·python·json
2401_858286118 小时前
OS55.【Linux】理解信号量(不是信号)
linux·运维·服务器·计数器·信号量
爱看书的小沐9 小时前
【小沐学CAD】基于OCCT读取和显示STEP模型文件(QT、MFC、glfw)
qt·mfc·opengl·stp·step·opencascade·occt
零基础的修炼10 小时前
Linux网络---数据链路层
linux·服务器·网络
小草儿79911 小时前
PG18备份恢复
linux·运维·服务器
Mikowoo00711 小时前
KaLi系统基本使用
运维·服务器
aaaffaewrerewrwer11 小时前
2026年常用HEIC转JPG在线工具推荐(支持批量转换)
服务器·图像处理