天天看点

linux下date命令获取及设置系统时间

一、获取时间

date:获取当前系统日期及时间

按格式获取时间:date +%Y-%m-%d_%H:%M:%S

[email protected]:~$ date
2020年 12月 24日 星期四 21:30:22 CST
[email protected]:~$ date +%Y-%m-%d_%H:%M:%S
2020-12-24_21:46:13
           

%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 小时制)

[email protected]:~$ date +%H
21
[email protected]:~$ date +%I
09
[email protected]:~$ date +%k
21
[email protected]:~$ date +%l
 9
[email protected]:~$ date +%M
49
[email protected]:~$ date +%p
下午
[email protected]:~$ date +%r
下午 09时49分18秒
[email protected]:~$ date +%s
1608817767
[email protected]:~$ date +%S
30
[email protected]:~$ date +%T
21:49:36
           

%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)

[email protected]:~$ date +%X
21时50分45秒
[email protected]:~$ date +%Z
CST
[email protected]:~$ date +%A
星期四
[email protected]:~$ date +%b
12月
[email protected]:~$ date +%B
十二月
[email protected]:~$ date +%c
2020年12月24日 星期四 21时51分01秒
[email protected]:~$ date +%d
24
[email protected]:~$ date +%D
12/24/20
[email protected]:~$ date +%h
12月
[email protected]:~$ date +%j
359
           

%m : 月份 (01..12)

%U : 一年中的第几周 (00..53) ( 以 Sunday 为一周的第几天的情形)

%w : 一周中的第几天 (0..6)

%W :一年中的第几周 (00..53) ( 以 Monday 为几周的第几天的情形)

%x : 直接显示日期 (mm/dd/yy)

%y : 年份的最后两位数字 (00.99)

%Y : 完整年份 (0000..9999)

[email protected]:~$ date +%m
12
[email protected]:~$ date +%u
4
[email protected]:~$ date +%w
4
[email protected]:~$ date +%W
51
[email protected]:~$ date +%x
2020年12月24日
[email protected]:~$ date +%y
20
[email protected]:~$ date +%Y
2020
           

二、设置时间

date -s:设置系统日期及时间,时间日期的设置需要root权限

date -s 20201224      //设置成2020年12月24日,时间设置成00:00:00

date -s 2020-12-24

date -s 12:20:30       //设置时间为12:20:30

[email protected]:~$ sudo date -s 20201224
2020年 12月 24日 星期四 00:00:00 CST
[email protected]:~$ sudo date -s 2020-12-25
2020年 12月 25日 星期五 00:00:00 CST
[email protected]:~$ sudo date -s 12:20:30
2020年 12月 24日 星期四 12:20:30 CST
           

继续阅读