前言:
在进行程序开发或调试的时候,我们经常会回去Ubuntu系统的时间,有时只是单纯的想查看时间,但我们更多的时候是想通过系统时间去做一些事情,例如通过时间命令一些文件夹或者文件,等等。
小先生提示:
以下对date的使用均仅限于以Unix为基础的系统,嵌入式平台或者Android平台上,对date命令做了简化处理,所以并不适用,请谨记!
小先生的干货:
下面是官方对date的使用讲解,看的是不是有点... ...
用法:date [选项]... [+格式]
或:date [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]]
Display the current time in the given FORMAT, or set the system date.
必选参数对长短选项同时适用。
-d, --date=STRING display time described by STRING, not 'now'
-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-0600
-R, --rfc-2822 output date and time in RFC 2822 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
-u, --utc, --universal print or set Coordinated Universal Time (UTC)
--help 显示此帮助信息并退出
--version 显示版本信息并退出
接下来小先生将会通过几个用例进行部分参数的说明:
用例1:获取某一天这个时刻的系统时间并以“年月日_时分秒”显示
$ date -d "xxx" +"%Y%m%d_%H%M%S"
说明:xxx:指的是你想显示的那一天的一个字符串描述,例如,今天可以用today、now等,明天可以用tomorrow(貌似只能使用这个),前天或前几天可以用yesterday,1 days ago,n days ago。
效果:表示20180315_203053前两天的这个时刻
date -d "2 days ago" +"%Y%m%d_%H%M%S"
20180313_203053
用例2:获取前一小时的当前时刻
$ date -d "(-)n hours" +"%Y%m%d_%H%M%S"
说明:n表示你要去的时间与当前时间相差的小时数,加上“-”代表你要回去n小时,不要减号表示你要到的未来n小时。
效果:如果想回到2个小时前
$ date -d "-2 hours" +"%Y%m%d_%H%M%S"
20180315_193357
备注:"%Y%m%d_%H%M%S"的显示可以根据读者喜好自行添加和删减,也可以变更间隔符等等。
用例3:设置时间
$ date -s "2018-03-15 20:43:00"
说明:-s表示要设置时间了,但是后面的参数可以随意,可以只设置年月日,也可以时分,秒就算了,等等就到了,哈哈哈。
效果:由于我的时间相当准,就不演示了,呵呵呵~。
未完待续~~~