检查日期参数是否采用yyyy-mm-dd格式和正确的日期范围

时间:2016-10-07 17:13:09

标签: shell unix ksh

有没有办法检查日期参数是否在正确的日期范围内,例如

  

2016-10-32或2016-09-31应显示为无效

我可以使用下面的代码

找到正确的参数yyyy-mm-dd
if [[ $1 =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]]
then echo "Date $1 is in valid format (YYYY-MM-DD)"
else echo "Date $1 is in an invalid format (not YYYY-MM-DD)"
fi

如何检查日期是否在正确的日期范围

2 个答案:

答案 0 :(得分:1)

将有效性检查委托给date根据需要更改消息

$ d='2016-10-32'; if date -d "$d" &>/dev/null; then echo "$d is OK"; else echo "$d is incorrect"; fi
2016-10-32 is incorrect

$ d='2016-10-31'; if date -d "$d" &>/dev/null; then echo "$d is OK"; else echo "$d is incorrect"; fi
2016-10-31 is OK

答案 1 :(得分:0)

回应karakfa的建议,使用GNU日期进行验证。使用简单的词法比较显示如何检查日期是在一个范围内

#!/bin/bash
date=$1
start="2016-05-01"
end="2016-09-01"
ymd=$(date -d "$date" +%F) || exit 1
# unfortunately, bash does not have a "<=" operator for strings
if [[ ($start < $ymd || $start = $ymd) && ($ymd < $end || $ymd = $end) ]]; then
    echo "$date in range"
else
    echo "$date not in range"
fi

正如我们所见,date对它接受的内容非常自由

$ bash datecheck.sh "sept 1"
sept 1 in range
$ bash datecheck.sh "sept 2"
sept 2 not in range
$ bash datecheck.sh "sept 31"
date: invalid date ‘sept 31’