|
发表于 2005-7-3 11:24:17
|
显示全部楼层
abs-guide中有一个计算两个日期中天数的例子,但它的格式是mm/dd/yyyy:
以下来自comp.unix.shell
在cus的fag上看到过一个date2julian()函数,把公历日期转换儒略日计数(Julian Day Count),然后就可以方便地计算出两个日期间相差的天数了
这个应该比较符合楼主需求
- # Date calculations using Korn shell (ksh88)
- # Tapani Tarvainen July 1998, May 2000
- # This code is in the public domain.
- # Julian Day Number from calendar date
- date2julian() # day month year
- {
- typeset -i day month year tmpmonth tmpyear
- day=$1; month=$2; year=$3
- ((tmpmonth = 12 * year + month - 3))
- ((tmpyear = tmpmonth / 12))
- print $(( (734 * tmpmonth + 15) / 24 - 2 * tmpyear + \
- tmpyear/4 - tmpyear/100 + tmpyear/400 + day + 1721119 ))
- }
复制代码
处理各种不同的日期格式。
- #!/bin/ksh
- ###########################################################################
- # Date calculations using Korn shell (ksh88)
- # Tapani Tarvainen July 1998, May 2000
- # This code is in the public domain.
- # Julian Day Number from calendar date
- date2julian() # day month year
- {
- typeset -i day month year tmpmonth tmpyear
- day=$1; month=$2; year=$3
- ((tmpmonth = 12 * year + month - 3))
- ((tmpyear = tmpmonth / 12))
- print $(( (734 * tmpmonth + 15) / 24 - 2 * tmpyear + \
- tmpyear/4 - tmpyear/100 + tmpyear/400 + day + 1721119 ))
- }
- ###
- # Matt's Added formatting
- ###
- # Store input dates
- date1=$1
- date2=$2
- # Get the dates into their respective fields. Uncomment the format of
- # date input being used.
- # YYYYMMDD
- year1=${date1%????}; mmdd1=${date1#????}; month1=${mmdd1%??}; day1=${mmdd1#??}
- year2=${date2%????}; mmdd2=${date2#????}; month2=${mmdd2%??}; day2=${mmdd2#??}
- # YYYY/MM/DD or YYYY/M/D
- #print $date1 |IFS=/ read year1 month1 day1
- #print $date2 |IFS=/ read year2 month2 day2
- # MM/DD/YY or M/D/YYYY
- #print $date1 |IFS=/ read month1 year1 day1
- #print $date2 |IFS=/ read month2 year2 day2
- # Calculate and print the difference between dates (date2 - date1)
- print -- "$(($(date2julian $day2 $month2 $year2) - $(date2julian $day1 \
- $month1 $year1)))"
复制代码
BASH需要做一些相应修改。 |
|