Chinaunix首页 | 论坛 | 博客
  • 博客访问: 919831
  • 博文数量: 127
  • 博客积分: 3812
  • 博客等级: 中校
  • 技术积分: 1859
  • 用 户 组: 普通用户
  • 注册时间: 2008-04-14 16:50
文章分类

全部博文(127)

文章存档

2015年(2)

2014年(9)

2013年(10)

2012年(25)

2011年(5)

2010年(35)

2009年(20)

2008年(21)

分类: LINUX

2014-03-26 11:15:39

     

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

############################################
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"

> date +%s
1302987605
> 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()等基本的日期函数的用法

阅读(900) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~