简体   繁体   中英

Bash validate 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.

I came up with this little function:

function isDateInvalid()
{
  date -d "$1" "+%m/%d/%Y" > /dev/null 2>&1
  res=$?
  echo "$res"
}

isDateInvalid "2012-02-219"
1

isDateInvalid "2012-02-29"
0
for y in {2013..2014}; do
  for m in {01..12}; do
    for d in {01..31}; do
      [[ ! "`date -jf %Y%m%d $y$m$d +%Y%m%d`" = "$y$m$d" ]] && continue
      echo $y.$m.$d
    done
  done
done

if strings match, loop will proceed ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM