日期格式的条件语句



我必须验证用户输入的日期。接受的日期格式为'+%m/%d/%Y' (04/10/1999)

我还必须验证第一个参数是否大于或等于第二个参数(也是一个日期)。例如:10/04/2000 10/04/1999,这将返回'1st应该大于2nd'

#operational statement
if [ "$1" -gt "$2" ]; then
echo "1st should be greater than 2nd"
exit 255
fi #having error of integer expression expected 
#validate inputted date
if [ "$1"  -ne `date -d '+%m/%d/%Y'` ] || [ "$2" -ne `date -d '+%m/%d/%Y'` ];
then
echo "Invalid. Follow [MM/DD/YY] Format"
exit 255
fi #i think there is a mistake with my condition but can't figure it out.
#!/bin/sh
# validation
for date do
case $date in
[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]);;
*) echo "$date: invalid, must be MM/DD/YYYY" >&2; die=1
esac
done
[ "$die" ] && exit 1
# sort dates (new to old)
printf '%sn' "$1" "$2" |
sort -rt / -k 3,3 -k 1,2 |
sed '1ais newer than'

或者不排序,而是将单位从大到小排列,去掉非数字,然后比较:

printf '%sn' "$1" "$2" |
{ IFS=/
read m1 d1 y1
read m2 d2 y2
if [ "$y1$m1$d1" -gt "$y2$m2$d2" ]; then
echo "$1 is newer than $2"
else
echo "$2 is newer than $1"
fi; }

这个问题没有标记bash,所以这是POSIX shell。如果可以控制日期格式,可以选择YYYYMMDD,这样可以直接比较([ "$1" -gt "$2" ])。

相关内容

  • 没有找到相关文章

最新更新