=Start=
缘由:
在程序中用到和日期相关的循环时,可能会需要提前确定两个日期之间的天数;还有就是在日常的一些记录中也会想了解两个日期之间的天数;总之,这样的需求是很多的。
正文:
参考解答:
使用GNU的date命令,它允许你通过「-d」选项指定(它能识别的)任意格式的日期,然后通过「+%s」选项将日期转换成从「1970-01-01 00:00:00 UTC」以来经过的秒数,两者相减然后除以一天中包含的秒数(24*60*60=86400秒)即可知道两个日期之间相距的天数。
datediff() { d1=$(date -d "$1" +%s) d2=$(date -d "$2" +%s) echo $(( (d1 - d2) / 86400 )) days}$ datediff '1 Nov' '1 Aug'91 days$ datediff 2016-12-10 2016-12-46 days$ datediff 2016-12-10 2016/12/46 days$ datediff 2016-12-4 2016-12-10-6 days |
&
bash-4.2$ mysql <<< "select datediff(current_date,'1980-06-14')"datediff(current_date,'1980-06-14')13332bash-4.2$ psql <<< "select current_date-'1980-06-14'" ?column?---------- 13332(1 row)bash-4.2$ sqlite2 <<< "select julianday('now')-julianday('1980-06-14');"13332.1524537035 |
&
$ echo $(($(($(date -d "2010-06-01" "+%s") - $(date -d "2010-05-15" "+%s"))) / 86400)) |
&
$ cat > datediff.sh#!/bin/bashfirstdate=$1;secondate=$2;fullyear=$(date -d@$(( ( $(date -ud "$secondate" +'%s') - $(date -ud "$firstdate" +'%s') ) )) +'%Y years %m months %d days %H hours %M minutes %S seconds')yearsubtraction=$(( $(echo $fullyear | sed -r 's/^([0-9]+).*/\1/') - 1970 ))if [ $yearsubtraction -le '0' ]; then echo $fullyear | sed -r "s/^([0-9]+) years //"else echo $fullyear | sed -r "s/^([0-9]+) /$(printf %02d $yearsubtraction) /"fi$ chmod +x datediff.sh$ ./datediff.sh '2013-07-22 11:55:19' '2015-12-25 02:00:13'02 years 06 months 04 days 16 hours 04 minutes 54 seconds$ ./datediff.sh '2013-07-22 11:55:19' '2013-12-25 02:00:13'06 months 05 days 16 hours 04 minutes 54 seconds |
参考链接:
- http://stackoverflow.com/questions/4946785/how-to-find-the-difference-in-days-between-two-dates
- http://stackoverflow.com/questions/3385003/shell-script-to-get-difference-in-two-dates
- http://unix.stackexchange.com/questions/24626/quickly-calculate-date-differences
=END=
《“Shell中如何计算两个日期之间的天数?”》 有 1 条评论
如何确定每个月的英文缩写?
`
先给结果:
(‘Jan’, ‘Feb’, ‘Mar’, ‘Apr’, ‘May’, ‘Jun’, ‘Jul’, ‘Aug’, ‘Sep’, ‘Oct’, ‘Nov’, ‘Dec’,)
再说方法:
for i in $(seq 0 11);do
# echo $i
date -d “2017-01-01 + “$i” month” -R | awk ‘{print $3}’
done
`
http://stackoverflow.com/questions/28226229/bash-looping-through-dates
http://stackoverflow.com/questions/2655883/bash-shell-date-parsing-start-with-specifc-date-and-loop-through-each-day-in-mo
http://unix.stackexchange.com/questions/98296/convert-month-number-to-month-name