代码改变世界

Shell学习笔记_时间计算[转]

2012-08-13 11:02  tetang1230  阅读(331)  评论(0编辑  收藏  举报

在工作中,经常会写一些脚本,而关于日期的计算更是经常会碰到的问题,在网上搜索并整理了下常用的日期计算脚本。

############################################
linux 时间计算函数
############################################

自19700101000000以来的秒数
date "+%s"

昨天的日期
date -d '1 days ago' "+%Y%m%d%H%M%S"

明天的日期
date -d '1 days' "+%Y%m%d%H%M%S"

1小时前的时间
date -d '1 hours ago' "+%Y%m%d%H%M%S"

1小时后的时间
date -d '1 hours ' "+%Y%m%d%H%M%S"

1分钟前的时间
date -d '1 minutes ago' "+%Y%m%d%H%M%S"

1分钟后的时间
date -d '1 minutes ' "+%Y%m%d%H%M%S"

1秒前的时间
date -d '1 seconds ago' "+%Y%m%d%H%M%S"

1秒后的时间
date -d '1 seconds ' "+%Y%m%d%H%M%S"

将某一时间转换为自19700101000000以来的秒数
date +%s -d '1990-01-01 01:01:01'

将时间戳转鬼换为日期格式
date -d '1970-01-01 UTC '$1' seconds' +"%Y-%m-%d %T"

mouse@linux:~/temp> date +%s
1302987605
mouse@linux:~/temp> date -d '1970-01-01 UTC '1302987605' seconds' +"%Y-%m-%d %T"
2011-04-17 05:00:05

 

时间差计算方法
原理:同样转成时间戳,然后计算天,时,分,秒

echo $(($(($(date +%s -d '2010-01-02') - $(date +%s -d '2010-01-01 00:00:00')))/3600))


补充说明:
shell 单括号运算符号:
a=$(date);
等同于:a=`date`;

双括号运算符:
a=$((1+2));
echo $a;
等同于:
a=`expr 1 + 2`

############################################
AIX 时间计算函数
############################################

strftime 将时间戳转日期
awk 'BEGIN{print strftime("%Y-%m-%d",1303039233)}'


将日期转为时间戳
awk 'BEGIN {printf("%d\n",mktime(2006" "8" "5" "15" "09" "0))}'

currentseconds=`awk 'BEGIN {printf("%d\n",systime())}'`
fiveminutesago=`expr $currentseconds - 300`
fiveminutesagotime=`awk -v fiveminutesago=$fiveminutesago 'BEGIN{print strftime("%Y%m%d%H%M%S",fiveminutesago)}'`
echo $fiveminutesagotime

 

在AIX上的AWK版本可能用不了strftime这些函数库,可以使用Perl

perl 常用的实例

得到日期的全部

perl -MPOSIX -le 'print strftime "%c", localtime();'
Sat 21 Aug 2010 07:54:34 AM CST

得到普通的指定的日期

perl -MPOSIX -le 'print strftime "%a %d %b %Y %H:%M:%S %Z", localtime();'
Sat 21 Aug 2010 07:54:11 CST

得到一个小时以前的时间

perl -MPOSIX -le 'print strftime "%c", localtime(time()-3600);'
Sat 21 Aug 2010 06:55:54 AM CST

得到一天前的时间

perl -MPOSIX -le 'print strftime "%Y%m%d%H%M%S", localtime(time()-86400);'

研究下: mktime() strftime(), systime()等基本的日期函数的用法