Linux下的时间编程

时间相关命令

很多 shell 脚本里面需要打印不同格式的时间或日期,以及要根据时间和日期执行操作。延时通常用于脚本执行过程中提供一段等待的时间。日期可以以多种格式去打印,也可以使用命令设置固定的格式。在类 UNIX 系统中,日期被存储为一个整数,其大小为自世界标准时间(UTC)1970 年 1 月 1 日 0 时 0 分 0 秒起流逝的秒数。

设定时间:

date -s                  //设置当前时间,只有 root 权限才能设置,其他只能查看
date -s 20161226         //设置日期,但是这样会把具体时间设置成 00:00:00
date -s 01:01:01         //设置具体时间,不会对日期做更改
date -s "01:01:01 2016-12-26"  //这样可以设置全部时间
date -s "01:01:01 20161226"    //这样可以设置全部时间
date -s "2016-12-26 01:01:01"  //这样可以设置全部时间
date -s "20161226 01:01:01"    //这样可以设置全部时间

描述

Linux下使用struct tm结构体描述时间,如下:

struct tm {
    int tm_sec;   /*秒:取值区间为[0,59] */
    int tm_min;   /*分:取值区间为[0,59] */
    int tm_hour;  /*时:取值区间为[0,23] */
    int tm_mday;  /*一个月中的日期:取值区间为[1,31] */
    int tm_mon;   /*月份(从一月开始,0 代表一月):取值区间为[0,11] */
    int tm_year;  /*年份:其值等于实际年份减去 1900 */
    int tm_wday;  /*星期:取值区间为[0,6],其中 0 代表星期天,1 代表星期一,以此类推 */
    int tm_yday;  /*从每年的 1 月 1 日开始的天数:取值区间为[0,365] */
    int tm_isdst; /*夏令时标识符,实行夏令时的时候,tm_isdst 为正。不实行夏令时的时候,tm_isdst 为 0 */
};
#include<time.h>
time_t time(time_t *t);
char *ctime(const time_t *timep)
struct tm *gmtime(const time_t *timep);
char *asctime(const struct tm *tm)
struct tm *localtime(const time_t *timep);
  • time 函数会返回从公元 1970 年 1 月 1 日的 UTC 时间从 0 时 0 分 0 秒算起到现在所经过的秒数。如果 t 并非空指针的话,此函数也会将返回值存到 t 指针所指的内存。
  • ctime 函数将日历时间转化为本地时间的字符串形式。
  • gmtime 函数将日历时间转换为格林威治时间。
  • asctime 函数将格林威治时间转化为字符串。
  • localtime 函数将日历时间转换为本地时间。
#include<stdio.h>
#include<time.h>
int main()
{
    /*获取日历时间,从1970-1-1 0点到现在的秒数.*/
    time_t n = time(NULL);
    printf("n=%d\n", n);
    /*将日历时间转换为格林威治时间*/
    struct tm *p = gmtime(&n);
    printf("%4d-%d-%d %d:%d:%d\n", 1900+p->tm_year, 1+p->tm_mon, p->tm_mday, p->tm_hour, p->tm_min, p->tm_sec);
    /*将日历时间转换为本地时间*/
    p = localtime(&n);
    printf("%4d-%d-%d %d:%d:%d\n", 1900+p->tm_year, 1+p->tm_mon, p->tm_mday, p->tm_hour, p->tm_min, p->tm_sec);
    return 0;
}

Updated: