- 论坛徽章:
- 0
|
还是日期计算!!
...
大家过奖了。
To quakelee:
是啊,具体应用过程中是要调试一下的,上面的给出的代码只是个骨架,实际中是应该把可能遇到的情况考虑进去。在这里我给出一些情况,如参数中是否有非法字符、字串太长、太短、含有空格、日期超出范围……等等,但也不可能考虑周全,只能是具体情况具体分析,根据自己的要求来完善。
另外,上面的帖子中漏掉了最后一句打印语句,我今天才看到。居然你也没提起!
修改后代码,供参考:
- #!/bin/sh
- # since we have to validate the date string more than once
- # put the leap year algorithm in subroutine, should be easy
- # to be invoked.
- leap() {
- case $1 in
- 1|3|5|7|8|10|12) Max=31;;
- 4|6|9|11) Max=30;;
- 2) if [ `expr $Year % 4` -eq 0 -a `expr $Year % 100` -ne 0 -o \
- `expr $Year % 400` -eq 0 ]; then
- Max=29
- else
- Max=28
- fi
- ;;
- *) Max=0
- esac
- echo $Max
- }
- if [ $# -eq 1 ]; then
- DateString=$1
- # Len=${#DateString} ## ksh or bash user can use this statement
- ## otherwise use the following expression
- Len=`expr "$DateString" : '.*'`
- if [ $Len -gt 8 ]; then
- echo "Date string too long!"
- exit 1
- elif [ $Len -lt 8 ]; then
- echo "Date string too short!"
- exit 1
- fi
- echo $DateString | grep '[^0-9]' > /dev/null 2>&1
- if [ $? -eq 0 ]; then
- echo "Invalid character(s) in date string! "
- exit 1
- fi
- Year=`echo $DateString | cut -b 1-4`
- Month=`echo $DateString | cut -b 5-6`
- Month=`expr $Month - 0` # remove leading zero
- Date=`echo $DateString | cut -b 7-8`
- DateMax=`leap $Month`
- if [ $Month -gt 12 -o $Month -lt 1 -o $Date -gt $DateMax -o $Date -lt 1 ]; then
- echo "Invalid date string format! either month or date range exceeds. "
- exit 1
- fi
-
- else
- Year=`date +%Y`
- Month=`date +%m`
- Date=`date +%d`
- fi
- Date=`expr $Date - 1`
- if [ $Date -eq 0 ]; then
- Month=`expr $Month - 1`
- if [ $Month -eq 0 ]; then
- Year=`expr $Year - 1`
- Month=12
- Date=31
- else
- Date=`leap $Month`
- fi
- fi
- if [ $# -ge 2 ]; then
- echo "Only ONE argument required!
- Parameters will be discarded and use default current date"
- fi
- printf "%04d/%02d/%02d\n" $Year $Month $Date
复制代码 |
|