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();
}
相关推荐
枷锁—sha10 分钟前
【DVWA系列】——CSRF——Medium详细教程
android·服务器·前端·web安全·网络安全·csrf
枷锁—sha11 分钟前
跨站请求伪造漏洞(CSRF)详解
运维·服务器·前端·web安全·网络安全·csrf
scuter_yu11 分钟前
腾讯云云服务器深度介绍
服务器·云计算·腾讯云
群联云防护小杜27 分钟前
深度隐匿源IP:高防+群联AI云防护防绕过实战
运维·服务器·前端·网络·人工智能·网络协议·tcp/ip
van叶~42 分钟前
Linux探秘坊-------15.线程概念与控制
linux·运维·服务器
2301_780789665 小时前
UDP和TCP的主要区别是什么
服务器·网络协议·web安全·网络安全·udp
一个龙的传说8 小时前
linux 常用命令
linux·服务器·zookeeper
斯是 陋室10 小时前
在CentOS7.9服务器上安装.NET 8.0 SDK
运维·服务器·开发语言·c++·c#·云计算·.net
肥or胖11 小时前
【FFmpeg 快速入门】本地播放器 项目
开发语言·qt·ffmpeg·音视频
莫到空离12 小时前
LVS三种模式实战
linux·服务器·网络