文章摘要:
本文介绍了linux操作系统关于时间的处理命令及应用程序中对系统时间的操作。


系统命令:

查看当前时间日期:

# date
2019年 06月 14日 星期五 10:28:38 CST

设置时间日期:
日期和时间之间有空格,所以要用引号括起来:

# date -s '2018-05-12 10:30:00'
2018年 05月 12日 星期五 10:30:00 CST

# date -s '18-05-12 10:30:00'
2018年 05月 12日 星期五 10:30:00 CST

# date -s '05/12/08 10:30:00'
2018年 05月 12日 星期五 10:30:00 CST
# date -s 2019-06-14
2019年 06月 14日 星期五 00:00:00 CST
# date -s 10:30:00
2019年 06月 14日 星期五 10:30:00 CST

1.日期格式: 月/日/年 或者 年-月-日;
2.只有日期无时分秒时,时分秒值为0;
3.只有时分秒无日期时,保持当前日期不变。


查看硬件时钟(RTC):

$ hwclock
2019年06月14日 星期五 14时42分06秒  -0.776878 seconds

修改硬件时钟(RTC):

# hwclock --set --date="06/12/19 14:55:00" 

硬件时钟同步至系统时钟:

# hwclock --hctosys

系统时钟同步至硬件时钟:

# hwclock --systohc

时区设置:
在/usr/share/zoneinfo/目录下找到对应的时区文件复制到/etc/localtime即可。


应用程序编程:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>
#include <stdint.h>
    
int main(int argc, char **argv)
{
  int ret;
  struct timeval tv;
  struct timezone tz;
  struct tm *ptm;
  struct tm stime;
  time_t t;

  //--------- 获取自1970年以来的秒数(UNIX时间戳)
  t = time(NULL);
  printf("time() = %d\r\n", t);
  //--------- 获取自1970年以来的秒数,微秒,时区
  gettimeofday(&tv, &tz);     // Linux不能获取时区值(时区参数可用NULL)
  printf("%d.%d\r\n", tv.tv_sec, tv.tv_usec);
  //------ 将timeval格式时间转换为年月日格式(格林尼治时间)
  ptm = gmtime(&tv.tv_sec);
  printf("%d-%02d-%02d %02d:%02d:%02d\r\n",
         ptm->tm_year + 1900, // 年 - 自1900来以来的年数
         ptm->tm_mon,         // 月 - {0,11},需要加1换算
         ptm->tm_mday,        // 日 - {0,31}
         ptm->tm_hour,        // 时 — {0,23}
         ptm->tm_min,         // 分 - {0,59}
         ptm->tm_sec);        // 秒 - {0,59}
  //------ 将timeval格式时间转换为年月日格式(本地时间)
  ptm = localtime(&tv.tv_sec);
  printf("%d-%02d-%02d %02d:%02d:%02d\r\n",
         ptm->tm_year + 1900, // 年 - 自1900来以来的年数
         ptm->tm_mon,         // 月 - {0,11},需要加1换算
         ptm->tm_mday,        // 日 - {0,31}
         ptm->tm_hour,        // 时 — {0,23}
         ptm->tm_min,         // 分 - {0,59}
         ptm->tm_sec);        // 秒 - {0,59}

  // 设置时间 ---------------------------------------
  stime.tm_year = 2019 - 1900;
  stime.tm_mon  = 5 - 1;
  stime.tm_mday = 12;
  stime.tm_hour = 01;
  stime.tm_min  = 02;
  stime.tm_sec  = 03;
  
  tv.tv_sec  = mktime(&stime); // 将年月日格式转化成unix时间戳
  tv.tv_usec = 0;

  ret = settimeofday(&tv, &tz); // 设置时间
  printf("ret = %d\r\n", ret);  // 成功返回0,其他值表示失败

  // 从实时时钟获取nS级时间(hwclock)----------------  
  struct timespec ts; 
  clock_gettime(CLOCK_REALTIME, &ts);
  printf("%d.%d\r\n", ts.tv_sec, ts.tv_nsec);

  return 0;
}

获取系统上电时间:

struct sysinfo info;
if (sysinfo(&info))
{
    return -1;
}
return info.uptime;