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();
}
相关推荐
fufu031120 小时前
俄罗斯方块
linux·运维·服务器
合作小小程序员小小店21 小时前
web安全开发,在线%服务器日志入侵检测%系统安全开发,基于Python,flaskWeb,正则表达式检测,mysql数据库
服务器·python·安全·web安全·flask·安全威胁分析·安全架构
路由侠内网穿透.1 天前
本地部署消息代理软件 RabbitMQ 并实现外部访问( Windows 版本 )
linux·运维·服务器·远程工作
wanhengidc1 天前
海外云手机是指什么
运维·服务器·游戏·智能手机·云计算
孙同学_1 天前
【Linux篇】System V IPC详解:共享内存、消息队列与信号量
linux·服务器
老歌老听老掉牙1 天前
解决 PyQt5 中 sipPyTypeDict() 弃用警告的完整指南
python·qt
虚伪的空想家1 天前
记录次etcd故障,fatal error: bus error
服务器·数据库·k8s·etcd
鸢尾掠地平1 天前
DNS的正向、反向解析的服务配置知识点及实验
运维·服务器·网络
顾安r1 天前
11.8 脚本网页 塔防游戏
服务器·前端·javascript·游戏·html
su3171 天前
rap2部署
linux·运维·服务器