QDateTime设置硬件时钟(RTC)及系统时钟

17 篇文章 1 订阅

#include <linux/rtc.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <stdio.h>
#include <time.h>
#include <unistd.h>

void convertDateTimeToTm(const QDateTime &dt, struct tm &tm)

{
    const int wday[8]={0,1,2,3,4,5,6,0};


    tm.tm_sec=dt.time().second();/* Seconds.[0-60](1 leap second)*/


    tm.tm_min=dt.time().minute();/* Minutes.[0-59] */


    tm.tm_hour=dt.time().hour();/* Hours. [0-23] */


    tm.tm_mday=dt.date().day();/*  Day.[1-31]  */


    tm.tm_mon=dt.date().month()-1;/* Month.[0-11]*/


    tm.tm_year=dt.date().year()-1900;/* Year- 1900.*/


    tm.tm_wday=wday[dt.date().dayOfWeek()];


    tm.tm_yday=dt.date().dayOfYear()-1;


    tm.tm_isdst=-1;/*DST.[-1/0/1]*/

}

/**
 * @brief writeRTC
 * @param pUTCTime
 * 参数为UTC时间,会自动把UTC时间转换为系统时间
 * @return
 */
bool writeRTC(struct tm *pUTCTime)
{
    int fd, retcal;


    fd = open("/dev/rtc",O_RDWR|O_NOCTTY); //打开设备


    if (fd == -1)
    {
        perror("error1");
    }


    struct rtc_time rtc_tm;
    rtc_tm.tm_year = pUTCTime->tm_year;
    rtc_tm.tm_mon = pUTCTime->tm_mon;
    rtc_tm.tm_mday = pUTCTime->tm_mday;
    rtc_tm.tm_hour = pUTCTime->tm_hour;
    rtc_tm.tm_min = pUTCTime->tm_min;
    rtc_tm.tm_sec = pUTCTime->tm_sec;


    retcal = ioctl(fd, RTC_SET_TIME, &rtc_tm);  //写入设备
    if (retcal == -1)
    {
        perror("error2");
    }


    close(fd);


    return fd!=-1 && retcal!=-1;
}

/**
 * @brief setDateTime
 * @param systemDT
 * 参数为系统时间
 */
void setDateTime(const QDateTime &systemDT)
{
    struct tm systemTime,utcTime;


    convertDateTimeToTm(systemDT, systemTime);
    convertDateTimeToTm(systemDT.toUTC(), utcTime);


    /**
     * stimt()等函数设置的是系统时钟,不会修改硬件时钟,系统重启后仍会加载硬件时钟。
     * */
    //设置硬件时钟
    writeRTC(&utcTime); //hwclock -r查看硬件时钟
    //设置系统时钟
    time_t t = mktime(&systemTime);
    stime(&t);
}

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值