Shell日期处理

在类Unix系统中,日期被存储成一个整数,其大小为自世界标准时间(UTC)①1970年1月1日0时0分0秒②起所流逝的秒数。这种计时方式称为纪元时或Unix时间。
(1) 读取日期:
[root@server-test ~]# date
Fri May 25 14:50:05 CST 2018
(2) 打印纪元时:
[root@server-test ~]# date +%s
1527231008

将日期串转换成纪元时,只需要这样即可实现:
[root@server-test ~]# date --date "Fri May 25 14:50:05 CST 2018" +%s
1527231005

(3) 用格式串结合 + 作为date命令的参数,可以按照你的选择打印出对应格式的日期。
[root@server-test ~]# date "+%d %B %Y"
25 May 2018

(4) 设置日期和时间:
# date -s "格式化的日期字符串"
[root@server-test ~]# date -s "Fri May 25 14:58:12 CST 2018"
Fri May 25 14:58:12 CST 2018

(5) 有时候,我们需要检查一组命令所花费的时间,可以使用以下代码:
#!/bin/bash
#文件名: time_take.sh
start=$(date +%s)
commands;
statements;
end=$(date +%s)
difference=$(( end - start))
echo Time taken to execute commands is $difference seconds.
另一种方法则是使用time<scriptpath>来得到执行脚本所花费的时间。

猜你喜欢

转载自www.cnblogs.com/rusking/p/9088855.html