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();
}
相关推荐
顶点多余14 分钟前
进程间通信 --- 共享内存篇(通信速度最快)
linux·服务器·jvm
liulilittle25 分钟前
LINUX RING BUFFER TUN/TAP 1
linux·服务器·网络·c++·信息与通信·通信
路由侠内网穿透.1 小时前
本地部署开源书签管理工具 LinkAce 并实现外部访问( Linux 版本)
linux·运维·服务器·网络·网络协议·开源
the sun342 小时前
Linux驱动开发:环境准备与报错处理
linux·运维·服务器
晨晖23 小时前
Linux命令3
linux·运维·服务器
Mike117.3 小时前
GBase 8a 数据同步实践:从 T+1 同步、实时镜像到一写多读的落地思路
java·服务器·数据库
智算菩萨3 小时前
使用免费托管平台搭建并部署静态与动态网页教程
服务器·html5·网页·网页部署
SeanDe4 小时前
【Linux `top` 命令详解(结合截图逐行拆解)】
linux·运维·服务器
桌面运维家4 小时前
Windows/Linux文件访问权限修改指南
linux·运维·服务器
欧云服务器5 小时前
魔方云批量更换ip教程
服务器·网络·tcp/ip