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();
}
相关推荐
christine-rr2 天前
linux常用命令(4)——压缩命令
linux·服务器·redis
東雪蓮☆2 天前
深入理解 LVS-DR 模式与 Keepalived 高可用集群
linux·运维·服务器·lvs
乌萨奇也要立志学C++2 天前
【Linux】进程概念(二):进程查看与 fork 初探
linux·运维·服务器
绿箭柠檬茶2 天前
Ubuntu 服务器配置转发网络访问
服务器·网络·ubuntu
我是菜鸟0713号2 天前
Qt 中 OPC UA 通讯实战
开发语言·qt
JCBP_2 天前
QT(4)
开发语言·汇编·c++·qt·算法
獭.獭.2 天前
Linux -- 信号【上】
linux·运维·服务器
路由侠内网穿透2 天前
本地部署 GPS 跟踪系统 Traccar 并实现外部访问
运维·服务器·网络·windows·tcp/ip
ZERO_pan2 天前
服务器装机遇到的问题
运维·服务器
l1t2 天前
利用DeepSeek实现服务器客户端模式的DuckDB原型
服务器·c语言·数据库·人工智能·postgresql·协议·duckdb