linux C time

一.linux date命令 设置系统时间,日期和时区
 ubuntu:~$ date --help
Usage: date [OPTION]... [+FORMAT]
  or:  date [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]]
Display the current time in the given FORMAT, or set the system date.

Mandatory arguments to long options are mandatory for short options too.
  -d, --date=STRING          display time described by STRING, not 'now'   //显示 datestr 中所设定的时间 (非系统时间)
      --debug                annotate the parsed date,
                              and warn about questionable usage to stderr
  -f, --file=DATEFILE        like --date; once for each line of DATEFILE
  -I[FMT], --iso-8601[=FMT]  output date/time in ISO 8601 format.
                               FMT='date' for date only (the default),
                               'hours', 'minutes', 'seconds', or 'ns'
                               for date and time to the indicated precision.
                               Example: 2006-08-14T02:34:56-06:00
  -R, --rfc-email            output date and time in RFC 5322 format.
                               Example: Mon, 14 Aug 2006 02:34:56 -0600
      --rfc-3339=FMT         output date/time in RFC 3339 format.
                               FMT='date', 'seconds', or 'ns'
                               for date and time to the indicated precision.
                               Example: 2006-08-14 02:34:56-06:00
  -r, --reference=FILE       display the last modification time of FILE
  -s, --set=STRING           set time described by STRING        //将系统时间设为 datestr 中所设定的时间
  -u, --utc, --universal     print or set Coordinated Universal Time (UTC)
      --help     display this help and exit
      --version  output version information and exit

FORMAT controls the output.  Interpreted sequences are:

  %%   a literal %
  %a   locale's abbreviated weekday name (e.g., Sun)
  %A   locale's full weekday name (e.g., Sunday)
  %b   locale's abbreviated month name (e.g., Jan)
  %B   locale's full month name (e.g., January)
  %c   locale's date and time (e.g., Thu Mar  3 23:05:25 2005)
  %C   century; like %Y, except omit last two digits (e.g., 20)
  %d   day of month (e.g., 01)
  %D   date; same as %m/%d/%y
  %e   day of month, space padded; same as %_d
  %F   full date; same as %Y-%m-%d
  %g   last two digits of year of ISO week number (see %G)
  %G   year of ISO week number (see %V); normally useful only with %V
  %h   same as %b
  %H   hour (00..23)
  %I   hour (01..12)
  %j   day of year (001..366)
  %k   hour, space padded ( 0..23); same as %_H
  %l   hour, space padded ( 1..12); same as %_I
  %m   month (01..12)
  %M   minute (00..59)
  %n   a newline
  %N   nanoseconds (000000000..999999999)
  %p   locale's equivalent of either AM or PM; blank if not known
  %P   like %p, but lower case
  %q   quarter of year (1..4)
  %r   locale's 12-hour clock time (e.g., 11:11:04 PM)
  %R   24-hour hour and minute; same as %H:%M
  %s   seconds since 1970-01-01 00:00:00 UTC
  %S   second (00..60)
  %t   a tab
  %T   time; same as %H:%M:%S
  %u   day of week (1..7); 1 is Monday
  %U   week number of year, with Sunday as first day of week (00..53)
  %V   ISO week number, with Monday as first day of week (01..53)
  %w   day of week (0..6); 0 is Sunday
  %W   week number of year, with Monday as first day of week (00..53)
  %x   locale's date representation (e.g., 12/31/99)
  %X   locale's time representation (e.g., 23:13:48)
  %y   last two digits of year (00..99)
  %Y   year
  %z   +hhmm numeric time zone (e.g., -0400)
  %:z  +hh:mm numeric time zone (e.g., -04:00)
  %::z  +hh:mm:ss numeric time zone (e.g., -04:00:00)
  %:::z  numeric time zone with : to necessary precision (e.g., -04, +05:30)
  %Z   alphabetic time zone abbreviation (e.g., EDT)

By default, date pads numeric fields with zeroes.
The following optional flags may follow '%':

  -  (hyphen) do not pad the field
  _  (underscore) pad with spaces
  0  (zero) pad with zeros
  ^  use upper case if possible
  #  use opposite case if possible

After any flags comes an optional field width, as a decimal number;
then an optional modifier, which is either
E to use the locale's alternate representations if available, or
O to use the locale's alternate numeric symbols if available.

Examples:
Convert seconds since the epoch (1970-01-01 UTC) to a date
  $ date --date='@2147483647'

Show the time on the west coast of the US (use tzselect(1) to find TZ)
  $ TZ='America/Los_Angeles' date

Show the local time for 9AM next Friday on the west coast of the US
  $ date --date='TZ="America/Los_Angeles" 09:00 next Fri'

GNU coreutils online help: <https://www.gnu.org/software/coreutils/>
Full documentation at: <https://www.gnu.org/software/coreutils/date>
or available locally via: info '(coreutils) date invocation'

扫描二维码关注公众号,回复: 11636647 查看本文章

1. Linux date命令可以用来显示或设定系统的日期与时间,在显示方面,使用者可以设定欲显示的格式,格式设定为一个加号后接数个标记,其中可用的标记列表如下:

时间方面:

  • % : 印出 %
  • %n : 下一行
  • %t : 跳格
  • %H : 小时(00..23)
  • %I : 小时(01..12)
  • %k : 小时(0..23)
  • %l : 小时(1..12)
  • %M : 分钟(00..59)
  • %p : 显示本地 AM 或 PM
  • %r : 直接显示时间 (12 小时制,格式为 hh:mm:ss [AP]M)
  • %s : 从 1970 年 1 月 1 日 00:00:00 UTC 到目前为止的秒数
  • %S : 秒(00..61)
  • %T : 直接显示时间 (24 小时制)
  • %X : 相当于 %H:%M:%S
  • %Z : 显示时区

日期方面:

  • %a : 星期几 (Sun..Sat)
  • %A : 星期几 (Sunday..Saturday)
  • %b : 月份 (Jan..Dec)
  • %B : 月份 (January..December)
  • %c : 直接显示日期与时间
  • %d : 日 (01..31)
  • %D : 直接显示日期 (mm/dd/yy)
  • %h : 同 %b
  • %j : 一年中的第几天 (001..366)
  • %m : 月份 (01..12)
  • %U : 一年中的第几周 (00..53) (以 Sunday 为一周的第一天的情形)
  • %w : 一周中的第几天 (0..6)
  • %W : 一年中的第几周 (00..53) (以 Monday 为一周的第一天的情形)
  • %x : 直接显示日期 (mm/dd/yy)
  • %y : 年份的最后两位数字 (00.99)
  • %Y : 完整年份 (0000..9999)

    实例:
    jasonfan@ubuntu:~$ date
    Fri 07 Aug 2020 06:42:47 AM UTC
    jasonfan@ubuntu:~$ date '+%c'
    Fri 07 Aug 2020 06:43:19 AM UTC
    jasonfan@ubuntu:~$ date '+%H'
    06
    jasonfan@ubuntu:~$ date '+%l'
     6
    jasonfan@ubuntu:~$ date '+%k'
     6
    jasonfan@ubuntu:~$ date '+%M'
    44
    jasonfan@ubuntu:~$ date '+%p'
    AM
    jasonfan@ubuntu:~$ date '+%r'
    06:45:05 AM
    jasonfan@ubuntu:~$ date '+%s'
    1596782721
    jasonfan@ubuntu:~$ date '+%S'
    43
    jasonfan@ubuntu:~$ date '+%T'
    06:45:53
    jasonfan@ubuntu:~$ date '+%X'
    06:46:16 AM
    jasonfan@ubuntu:~$ date '+%Z'
    UTC
    jasonfan@ubuntu:~$ date '+%a'
    Fri
    jasonfan@ubuntu:~$ date '+%A'
    Friday
    jasonfan@ubuntu:~$ date '+%b'
    Aug
    jasonfan@ubuntu:~$ date '+%B'
    August
    jasonfan@ubuntu:~$ date '+%c'
    Fri 07 Aug 2020 06:47:26 AM UTC
    jasonfan@ubuntu:~$ date '+%d'
    07
    jasonfan@ubuntu:~$ date '+%D'
    08/07/20
    jasonfan@ubuntu:~$ date '+%h'
    Aug
    jasonfan@ubuntu:~$ date '+%j'
    220
    jasonfan@ubuntu:~$ date '+%m'
    08
    jasonfan@ubuntu:~$ date '+%U'
    31
    jasonfan@ubuntu:~$ date '+%w'
    5
    jasonfan@ubuntu:~$ date '+%W'
    31
    jasonfan@ubuntu:~$ date '+%x'
    08/07/2020
    jasonfan@ubuntu:~$ date '+%y'
    20
    jasonfan@ubuntu:~$ date '+%Y'
    2020
    jasonfan@ubuntu:~$
    jasonfan@ubuntu:~$ date +%s                 //时间戳
    1596784081
    jasonfan@ubuntu:~$ date --date=@1596784081   //时间戳转换成日期
    Fri 07 Aug 2020 07:08:01 AM UTC
    jasonfan@ubuntu:~$ date -R
    Fri, 07 Aug 2020 07:11:12 +0000          //显示时区

2. 设置时间:
date -s 15:06:00

3. 时区GMT、UTC、DST、CST时区代表的意义
更多时区参考如下网站
http://www.timebie.com/cn/
https://datetime360.com/cn/
 

  GMT:Greenwich Mean Time 

格林威治标准时间 ; 英国伦敦格林威治定为0°经线开始的地方,地球每15°经度 被分为一个时区,共分为24个时区,相邻时区相差一小时;例: 中国北京位于东八区,GMT时间比北京时间慢8小时。

    UTC: Coordinated Universal Time

世界协调时间;经严谨计算得到的时间,精确到秒,误差在0.9s以内, 是比GMT更为精确的世界时间

    DST: Daylight Saving Time

夏季节约时间,即夏令时;是为了利用夏天充足的光照而将时间调早一个小时,北美、欧洲的许多国家实行夏令时;

    CST:

四个不同时区的缩写:

    Central Standard Time (USA) UT-6:00 美国标准时间
    Central Standard Time (Australia) UT+9:30 澳大利亚标准时间
    China Standard Time UT+8:00 中国标准时间
    Cuba Standard Time UT-4:00 古巴标准时间

4. linux时区
4.1 各种时区信息
$cd /usr/share/zoneinfo
4.2查询系统设置的时区
$ date -R
4.3设置系统时区
方法1: tzselect
$tzselect          //按提示选择

Therefore TZ='Asia/Shanghai' will be used.
Selected time is now:   Fri Aug  7 15:24:34 CST 2020.
Universal Time is now:  Fri Aug  7 07:24:34 UTC 2020.
You can make this change permanent for yourself by appending the line
        TZ='Asia/Shanghai'; export TZ
to the file '.profile' in your home directory; then log out and log in again.

Here is that TZ value again, this time on standard output so that you
can use the /usr/bin/tzselect command in shell scripts:
Asia/Shanghai

 方法2:
cp /usr/share/zoneinfo/$主时区/$次时区 /etc/localtime
例如:在设置中国时区使用亚洲/上海(+8)
cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime

二.linux 系统时钟和硬件时钟(RTC)
 linux系统有两个时钟:一个是由主板电池驱动的硬件时钟(Real Time Clock),也叫做RTC或者叫CMOS时钟。当操作系统关机的时候,用这个来记录时间,但是对于运行的系统是不用这个时间的;另一个时间是系统时钟(System clock)也叫内核时钟或者软件时钟,是由软件根据时间中断来进行计数的,内核时钟在系统关机的情况下是不存在的,所以,当操作系统启动的时候,内核时钟是要读取RTC时间来进行时间同步。并且在系统关机的时候将系统时间写回RTC中进行同步
1.查看系统时钟
#date
2.查看硬件时钟
#hwclock --show
3.系统时钟与硬件时钟同步
# hwclock --systohc    #以系统时钟为准,同步硬件时钟
# hwclock --hctosys    #以硬件时钟为准,同步系统时钟
4.服务器时间与系统时间同步
应用中需要与服务器时间同步
#apt-get install ntpdate
# ntpdate cn.pool.ntp.org        #同步北京时间  或
# ntpdate -u NTP_SERVER    #手动同步,指定时间服务器
ntp官网:
http://www.ntp.org/

二.数据结构
/usr/time.h 
1. important structer
1.1struct timeb结构:
主要有两个成员, 一个是秒, 另一个是毫秒, 精确度为毫秒. 

    struct timeb
    {
        time_t time;
        unsigned short millitm;
        short timezone;
        short dstflag;
    }; 

由函数int ftime(struct timeb *tp); 来获取timeb.

1.2 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],其中0代表1月1日,1代表1月2日,以此类推 */  
int tm_isdst;              /* 夏令时标识符,实行夏令时的时候,tm_isdst为正。不实行夏令时的进候,tm_isdst为0;不了解情况时,tm_isdst()为负。*/  
long int tm_gmtoff;     /*指定了日期变更线东面时区中UTC东部时区正秒数或UTC西部时区的负秒数*/   
const char *tm_zone;     /*当前时区的名字(与环境变量TZ有关)*/  
}; 

1.3 struct  timeval时间类型
struct timeval

time_t tv_sec; //秒 
 suseconds_t tv_usec; //微秒(10^-6)s   //毫秒(10^-3)s

 };


由int gettimeofday(struct timeval *tv, struct timezone *tz);获取.

 struct timezone结构的定义为: 

    struct timezone
    {
       int tz_minuteswest; /* 和Greewich时间差了多少分钟*/
       int tz_dsttime; /* 日光节约时间的状态 */
    };


1.4 struct   timespec 时间类型 
有两个成员,一个是秒,一个是纳秒, 所以最高精确度是纳秒
struct timespec
{
time_t tv_sec; //秒
long tv_nsec; //纳秒(10^-9)s 
};

一般由函数long clock_gettime (clockid_t which_clock, struct timespec *tp); 获取.

获取特定时钟的时间,时间通过tp结构传回,目前定义了6种时钟,分别是

   CLOCK_REALTIME               统当前时间,从1970年1.1日算起

  CLOCK_MONOTONIC              系统的启动时间,不能被设置

  CLOCK_PROCESS_CPUTIME_ID     进程运行时间

  CLOCK_THREAD_CPUTIME_ID      线程运行时间

  CLOCK_REALTIME_HR            CLOCK_REALTIME的高精度版本

  CLOCK_MONOTONIC_HR           CLOCK_MONOTONIC的高精度版本

  获取特定时钟的时间精度:

  long clock_getres(clockid_t );

  设置特定时钟的时间:

  long clock_settime(clockid_t ,struct timespec*);

  休眠time中指定的时间,如果遇到信号中断而提前返回,则由left_time返回剩余的时间:

   long clock_nanosleep(clockid_t ,int flag,timespec* time,timespec* left_time);

     clock_t类型, 由clock_t clock(); 返回获取.

      表示进程占用的cpu时间. 精确到微秒.

2.time_t
time_t 实际上是一个长整型,其值表示从1970年1月1日00时00分00秒(linux系统的Epoch时间)到当前时刻的秒数,由于time_t类型长度限制;(long型),它所表示的时间不能晚于2038年1月19日03时14分07秒(UTC)

三.linux 有关时间的函数:
1.asctime: 将时间和日期以字符串格式表示
2. clock: 取得进程占用CPU的大约时间
3. ctime: 将时间和日期以字符串格式表示
4. difftime:计算时间差距
5.ftime:取得目前的时间和日期
6.gettimeofday:取得目前时间
7.gmtime:取得目前的时间和日期
8.localtime:取得当地时间和日期
9.mktime:将时间结构数据转换成经过的秒数
10.settimerofday:设置目前时间
11.time:取得目前时间,返回秒
12.tzset:设置时区以供时间转换

1.time()函数
使用time()函数获取当前时间的time_t值,使用ctime()函数将time_t  转为当地时间字符串(返回值是字符串);

头文件:#include <time.h>
函数定义:time_t time(time_t *timer)
功能描述:该函数返回从1970年1月1日00时00分00秒至今所经过的秒数。如果time_t *timer非空指针,函数也会将返回值存到timer指针指向的内存。
返回值:成功则返回秒数,失败则返回((time_t)-1)值,错误原因存于errno中。

2.gmtime() 
将time_t 时间类型转换为tm结构体;

头文件:#include <time.h>
函数定义:struct tm *gmtime(const time_t *timep)
功能描述:gmtime( )将参数timep指向的time_t时间信息转换成以tm结构体表示的GMT时间信息,并以struct tm*指针返回。
GMT:GMT是中央时区,北京在东8区,相差8个小时,所以北京时间=GMT时间+8小时

3.localtime()  
将time_t 时间类型转换为tm结构体; 

头文件:#include <time.h>
函数定义:struct tm *localtime(const time_t *timep);
功能描述:localtime( )将参数timep指向的time_t时间信息转换成以tm结构体表示的本地时区时间(如北京时间= GMT+小时)。

4. asctime()
将struct tm转换为字符串形式

头文件:#include <time.h>
函数定义:char *asctime(const struct tm *p_tm);
功能描述:asctime( )将参数p_tm指向的tm结构体数据转换成实际使用的时间日期表示方法,并以字符串形式返回(与ctime函数相同)。字符串格式为:"Wed July 20 21:00:00 2019\n"。

5.mktime()
将tm结构体转换为time_t时间类型; 

头文件:#include <time.h>
函数定义:time_t mktime(struct tm *p_tm);
功能描述:mktime( )将参数p_tm指向的tm结构体数据转换成从1970年1月1日00时00分00秒至今的GMT时间经过的秒数。

6.ctime( )函数
头文件:#include <time.h>
函数定义:char *ctime(const time_t *timep);
功能描述:ctime( )将参数timep指向的time_t时间信息转换成实际所使用的时间日期表示方法,并以字符串形式返回。字符串格式为:"Wed July 20 21:00:00 2019"

7.difftime( )函数
头文件:#include <time.h>
函数定义:double difftime(time_t timep1, time_t timep2);
功能描述:difftime( )比较参数timep1和timep2时间是否相同,并返回之间相差秒数。

8.gettimeofday( )函数
头文件:#include <sys/time.h>
        #include <unistd.h>
函数定义:int gettimeofday(struct timeval *tv, struct timezone *tz);
功能描述:gettimeofday( )把目前的时间信息存入tv指向的结构体,当地时区信息则放到tz指向的结构体。


struct timezone原型:
struct timezone{  

int tz_minuteswest; /*miniutes west of Greenwich*/  

int tz_dsttime; /*type of DST correction*/  

};  

9.settimeofday( )函数
头文件:#include <sys/time.h>
        #include <unistd.h>
函数定义:int settimeofday(const struct timeval *tv, const struct timezone *gz);
功能描述:settimeofday( )把当前时间设成由tv指向的结构体数据。当前地区信息则设成tz指向的结构体数据。

c代码示例:

#include <stdio.h>
#include <time.h>
#include <sys/timeb.h>
#include <sys/time.h>
int main ()
{
   time_t rawtime;  //long int
   struct tm *info;
   /*  /usr/include/sys/time.h or timeb.h*/
   struct timeb tp;
   struct timeval tv;
   struct timezone tz;
   char buffer[80];
   long int seconds=-1;

   //time()
   seconds=time( &rawtime );  //time: get and return seconds since 1970.01.01/00:00:00 UTC
   printf("time:seconds since 1970.01.01/00:00:00 UTC = %ld\n",seconds);

   //gmtime() : convert the UTC seconds to date
   info=gmtime(&rawtime);
   printf("gmtime:%02d-%02d-%02d\n",(1900+info->tm_year),(1+info->tm_mon),info->tm_mday);

   //localtime()
   info = localtime( &rawtime );  //localtime: return local time

   //asctime()&ctime()
   printf("asctime to print local time:%s", asctime(info));  //asctime: print time as ascii format
   printf("ctime to print local time:%s", ctime(&rawtime));  //ctime: print time as ascii format

   //mktime(): convert tm struct to UTC seconds without the local timezone
   //use time() to get UTC seconds then use localtime() to convert UTC seconds to  struct tm which will have local timezone after localtime convert.then use mktime() to convert struct tm back to UTC seconds
   rawtime=mktime(info);
  printf("time()->localtime()->mktime(): %ld\n",rawtime);
   //ftime()
   ftime(&tp);
   printf("ftime->time:%ld\n",tp.time);
   printf("ftime->millitm:%d\n",tp.millitm);
   printf("ftime->timezone:%d\n",tp.timezone);
   printf("ftime->dstflag:%d\n",tp.dstflag);

   //gettimeofday(): get local time
   gettimeofday(&tv,&tz);
   printf("gettimeofday->tv_sec:%ld\n",tv.tv_sec);
   printf("gettimeofday->tv_usec:%ld\n",tv.tv_usec);
   printf("gettimeofday->tz_minuteswest:%d\n",tz.tz_minuteswest);
   printf("gettimeofday->tz_dsttime:%d\n",tz.tz_dsttime);

   return(0);
}


输出结果:
time:seconds since 1970.01.01/00:00:00 UTC = 1597040984
gmtime:2020-08-10
asctime to print local time:Mon Aug 10 06:29:44 2020
ctime to print local time:Mon Aug 10 06:29:44 2020
time()->localtime()->mktime(): 1597040984
ftime->time:1597040984
ftime->millitm:667
ftime->timezone:0
ftime->dstflag:0
gettimeofday->tv_sec:1597040984
gettimeofday->tv_usec:667770
gettimeofday->tz_minuteswest:0
gettimeofday->tz_dsttime:0

猜你喜欢

转载自blog.csdn.net/fanxianchao_2012/article/details/102562340
今日推荐