问题描述
我正在写一个shell脚本,并且为什么我的日期验证码不起作用,我感到困惑。我尝试以下解决方案,我发现类似的问题,但is_valid始终设置为1: date+%m /% d /%Y-d$ 12> 1> / dev / null
//或..
date -d2012-02-29> / dev / null 2& 1
is_valid = $?
#always设置为1,即使给定有效日期
如何正确验证日期格式?日期应该是有效的,如果格式为MM / DD / YYYY
我也试过这个解决方案:,但它总是拒绝日期。
Mac OS X附带的BSD date
不支持 -d
选项(或相反,它对于完全不同的东西使用 -d
。安装GNU date
,或使用以下内容来验证输入字符串:
date -f%Y-%m-%d-j2012-02-29> / dev / null 2& 1
-f
提供输入格式, -j
告诉 date
只是输出日期,而不是尝试设置系统时钟。
I'm writing a shell script and am confused as to why my date validation code is not working. I tried the following solutions to similar questions I found, but is_valid is always set to 1:
date "+%m/%d/%Y" -d "$1" 2>1 > /dev/null
//or..
date -d "2012-02-29" > /dev/null 2>&1
is_valid=$?
#always set to 1, even when given a valid date
How do I correctly validate the date format? The date should only be valid if in the format MM/DD/YYYY
I also tried this solution: Linux Bash - Date Format but it always rejected the date as well.
The BSD date
that ships with Mac OS X doesn't support the -d
option (or rather, it uses -d
for something entirely different). Either install GNU date
, or use the following to validate your input string:
date -f "%Y-%m-%d" -j "2012-02-29" >/dev/null 2>&1
The -f
provides the input format, and the -j
tells date
to simply output the date, not attempt to set the system clock.
这篇关于Bash验证日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!