Crane
Table_bottom

Search
Loading
Table_bottom

分类
Table_bottom

随机文章
Table_bottom

标签云
Table_bottom

最新评论
Table_bottom

链接
Table_bottom

功能
Table_bottom

计算两个日期的差值

Crane posted @ 2011年4月08日 05:58 in Linux with tags linux program shell 程序员 , 15793 阅读

记得今年早些时候看到百度员工出的那个视频,中间有一幕女主角在计算自己自出生以来已经生活了多少天,只见她熟练的打开excel,在A1中输入生日,在B1中输入当天日期,在C1中输入=B1-A1,立刻得到自己来到这个世上的时间,眼看过去了这么多天,自己当初的梦想实现了多少呢,……,剧情自此展开,不再追踪。

我看到这个的时候,想着cli控们有没有什么方法能实现同样的功能呢,无所不能的shell(我记得有人说过shell是完备的)啊,需要你的力量。

想了一下,使用了coreutils中的date命令,写成了如下shell脚本:

 

#/bin/sh
#
# this scrit is used to calculate the distance between two date.
# e.g. My birthday is 1988-12-29,today is 2011-04-01,I want to how
# many days I have been alive in this world.
# so use
#  daydis.sh 19881229 20110401

function error_msg(){
    echo -n This is a shell script to count days between date.
    echo '  usage: $0 date1 date2'
    echo -e '\tfor example, to calculate how many days between two date,'
    echo -e '\te.g. from 19881229 to 20110401'
    echo -e '\ttry: $0 19881229 20110401'
    exit
}
from=$1
to=$2
if [ ${#from} -ne 8 ] || [ ${#to} -ne 8 ];then
    error_msg
fi
if [ $(($1-$2)) -gt 0 ] ;then
    error_msg
fi
if [ ${from:0:4} -lt 1902 ] || [ ${to:0:4} -gt 2037 ];then
    echo "the year of date should range from 1902 to 2037."
    exit
fi
from=`eval date -d "$1" +%s`
#echo $from
to=`eval date -d "$2" +%s`
#echo $to
secdis=`echo $(($to-$from))`
#echo $secdis
daydis=`echo $(($secdis/3600/24))`

echo "from $1 to $2,there are $daydis day(s)."

原理是用到了日历时间,在UNIX系统中的时间定义是这样的,系统用一个time_t类型的变量来表示系统时间,它的值是从1970年1月1日00:00:00以来所经过的秒数的累计,程序中就是通过计算两个日期的这个秒数累计的差,然后把这个秒数差值转换成天数,即得到了我们要的答案。

得到一个日期的秒数累计(日历时间)可以用date命令来搞定,比如2011年4月1日,可以这样

$ date -d "20110401" +%s

1301587200

得到的那个1301587200就是一个秒数的累计,再做一些简单的算术运算就可以得到所要的结果。

PS:上面可以看到这个秒数已经累计到13亿了,而如果用一个32位整数来存放这个的话,有符号的最大也就是21亿多,貌似已经很靠近了,如果到了那一天会有什么问题呢?这就是著名的Year 2038 problem,不过不用担心,到那个时间还早着呢,这期间硬件变化,把32位的换成64位,或者干脆用一个浮点数来存这个,都不会出现这个问题。

seo service london 说:
2024年1月14日 00:25

Nice post. I discover something more difficult on diverse blogs everyday. It will always be stimulating to study content from other writers and employ a specific thing from their site

토토핫꽁머니 说:
2024年1月22日 19:43

Elegantly composed article. It will be steady to anybody who uses it, including me. Continue doing what you are doing - can't respite to peruse more posts. Gratitude for the valuable assistance.

벳365주소 说:
2024年1月22日 20:44

I exactly get what you mean. Thanks for posting. And I am too much happy to find this website on the world of Google.

카림가입코드 说:
2024年1月22日 21:28

I really loved reading your blog. It was very well authored and easy to undertand. Unlike additional blogs I have read which are really not tht good. I also found your posts very interesting. In fact after reading, I had to go show it to my friend and he ejoyed it as well!

사설토토 说:
2024年1月22日 21:53

you are so exciting! I don’t consider i’ve examine some thing like this before. So great to discover any other character with a few proper mind in this issue. Significantly.. Thanks for beginning this up. This website is some thing that is required at the net, a person with some originality! I quite like studying via a submit which can make males and females assume. Also, many thank you for allowing me to comment! Spot on with this write-up, i genuinely suppose this superb web site needs a remarkable deal more attention. I’ll likely be returning to peer more, thanks for the advice! I’m very thrilled to discover this page. I wanted to thanks on your time for this outstanding read!! I certainly truely favored every little bit of it and i also have you ever saved as a favourite to have a look at new matters to your internet site.

먹튀검증사이트 说:
2024年1月22日 22:13

When i receive anyone to this webpage and understand having useful information on identical issues.

로얄클럽블랙 说:
2024年1月22日 22:16

What i don’t realize is in fact how you’re no longer actually much more smartly-liked than you may be right now. You are very intelligent. You understand thus significantly on the subject of this matter, produced me for my part imagine it from so many various angles. Its like men and women are not involved unless it is something to do with Lady gaga! Your personal stuffs nice. Always maintain it up!

안전놀이터검증 说:
2024年1月22日 22:42

I must express some appreciation to the writer just for rescuing me from such a incident. Just after surfing around throughout the internet and obtaining strategies which are not helpful, I thought my life was well over. Being alive without the approaches to the problems you've resolved as a result of your good report is a critical case, and ones that could have in a negative way damaged my career if I had not noticed your blog. Your actual expertise and kindness in touching almost everything was priceless. I am not sure what I would've done if I hadn't come across such a stuff like this. I can at this moment look ahead to my future. Thanks a lot so much for your expert and sensible help. I won't hesitate to endorse your blog to anyone who needs care on this situation.

먹튀검증 说:
2024年1月22日 22:44

Can I just say such a relief to uncover one who really knows what theyre talking about on the web. You actually know how to bring a worry to light and make it important. More and more people have to read this and understand why side with the story. I cant believe youre less popular since you also definitely provide the gift.

먹튀사이트주소 说:
2024年1月22日 22:55

Easily, the article is actually the best topic on this registry related issue. I fit in with your conclusions and will eagerly look forward to your next updates

안전놀이터가입 说:
2024年1月22日 22:56

Kinds information sites in addition almost every a lot more stage will be entertaining in addition serviceable That appoints every person struck find refuge encore. My partner and i definitely can rapidly take hold of kinds nourish to settle well informed linked with just about any emails.

파워볼사이트 说:
2024年1月22日 23:11

You possess put an important kids.. Blesss intended for applying.. When i may want to review superior most current orders with this web log.. keep placing..

입플사이트추천 说:
2024年1月22日 23:19

Can I just say such a relief to uncover one who really knows what theyre talking about on the web. You actually know how to bring a worry to light and make it important. More and more people have to read this and understand why side with the story. I cant believe youre less popular since you also definitely provide the gift.

메이저놀이터 说:
2024年1月22日 23:27

Outstanding article and that i favor your attitude towards improving standards. Thanks for putting this material up. This really is Specifically what I have been seeking. Maintain blogging. Finding excited about reading your up coming post.

안전놀이터 说:
2024年1月22日 23:37

Hello. I want to ask a little something…is this a wordpress website as we are planning to be switching across to WP. In addition did you make this theme by yourself? Appreciate it.

사설토토 说:
2024年1月22日 23:44

Outstanding article and that i favor your attitude towards improving standards. Thanks for putting this material up. This really is Specifically what I have been seeking. Maintain blogging. Finding excited about reading your up coming post.

얀카지노검증 说:
2024年1月22日 23:51

Hmm… Lake know information sites running a corresponding issue, still lake rarely gave up on and your webpage. Lake put in during the product or service that will help populars in a similar fashion i’ll likely get styles concentrated primer.

큐브카지노먹튀 说:
2024年1月23日 00:00

I have not checked in here for some time because I thought it was getting boring, but the last few posts are good quality so I guess I will add you back to my everyday bloglist. You deserve it my friend :)

동행복권파워볼 说:
2024年1月23日 01:03

Have you ever considered about adding a little bit more than just your articles? I mean, what you say is fundamental and everything. Nevertheless think about if you added some great pictures or video clips to give your posts more, “pop”! Your content is excellent but with images and clips, this site could certainly be one of the most beneficial in its field. Fantastic blog!

토토커뮤니티순위 说:
2024年1月23日 01:13

My California Weight Loss diet invariably is an cost effective and versatile staying on your diet tv show made for people who find themselves planning to drop extra pounds and furthermore ultimately keep a much healthier habits. la weight loss

먹튀제보 说:
2024年1月23日 01:27

You have played out an incredible work on this article. It's extremely exact and profoundly subjective. You have even figured out how to make it comprehensible and simple to peruse. You have some genuine composing ability. Many thanks.

토토사이트 说:
2024年1月23日 01:59

I can see that you are an expert at your field! I am launching a website soon, and your information will be very useful for me.. Thanks for all your help and wishing you all the success in your business.

스카이파크가입 说:
2024年1月23日 02:04

You possess put an important kids.. Blesss intended for applying.. When i may want to review superior most current orders with this web log.. keep placing..

먹튀검증커뮤니티 说:
2024年1月23日 02:14

I appreciate everything you have added to my knowledge base. Admiring the time and effort you put into your blog and detailed information you offer.

소울 카지노 说:
2024年1月23日 02:21

Really amazing post. I just stumbled beside your blog. I will definitely suggest your blog to all of my friends. Thanks for sharing this valuable information for free

토토베이홍보방 说:
2024年1月23日 02:28

This web site is really a walk-through you discover the knowledge it suited you about this and didn’t know who to inquire about. Glimpse here, and you’ll undoubtedly discover it.

메이저사이트 순위 说:
2024年1月23日 02:36

I exactly get what you mean. Thanks for posting. And I am too much happy to find this website on the world of Google.

안전놀이터 说:
2024年1月23日 02:50

That is the excellent mindset, nonetheless is just not help to make every sence whatsoever preaching about that mather. Virtually any method many thanks in addition to i had endeavor to promote your own article in to delicius nevertheless it is apparently a dilemma using your information sites can you please recheck the idea. thanks once more

사설토토먹튀 说:
2024年1月23日 02:50

Beneath the you can have an understanding of it is important, consuming this solution presents among the many inbound links together with the exciting webpage:

배트맨토토가입 说:
2024年1月23日 03:01

When I read your article on this topic, the first thought seems profound and difficult. There is also a bulletin board for discussion of articles and photos similar to this topic on my site, but I would like to visit once when I have time to discuss this topic

토토사이트 说:
2024年1月23日 03:05

Wow, cool post. I'd like to write like this too - taking time and real hard work to make a great article... but I put things off too much and never seem to get started. Thanks though.

먹튀신고 说:
2024年1月23日 03:23

When I read your article on this topic, the first thought seems profound and difficult. There is also a bulletin board for discussion of articles and photos similar to this topic on my site, but I would like to visit once when I have time to discuss this topic

메이저사이트추천 说:
2024年1月23日 03:26

Easily, the article is actually the best topic on this registry related issue. I fit in with your conclusions and will eagerly look forward to your next updates

에볼루션카지노 说:
2024年1月23日 03:34

I as well believe thence , perfectly pent post! Youre so cool! I dont suppose Ive read something such as this before. So nice to seek out somebody by incorporating authentic ideas on this subject. realy i appreciate you for starting this up. this excellent website are some things that’s needed online, somebody after a little bit originality. helpful work for bringing something new to the web! You really should take part in a tournament for starters of the best blogs on-line. I am going to recommend this great site! Nice post! This is a very nice blog that I will definitively come back to more times this year! Thanks for informative post.

먹튀검증업체 说:
2024年1月23日 03:42

Outstanding article and that i favor your attitude towards improving standards. Thanks for putting this material up. This really is Specifically what I have been seeking. Maintain blogging. Finding excited about reading your up coming post.

벳매니아가입 说:
2024年1月23日 03:50

This is very beneficial, despite the fact that it'll be crucial that you aid click on in which website website link


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter