4

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.

Community
  • 1
  • 1
Cbas
  • 6,003
  • 11
  • 56
  • 87
  • I'm not experiencing the same result. When I run `date -d "2012-02-29 > /dev/null 2>&1" then "echo $?" I get `0`. – lurker Jan 19 '14 at 19:45
  • What does `date --version` print for you? (BTW, I get the same result as mbratch and Aleksey Izmailov.) – ruakh Jan 19 '14 at 19:54
  • It prints: "date: illegal option -- - \n usage: date ....." I'm using Mac OSX btw – Cbas Jan 19 '14 at 20:06
  • 1
    As you've now found out, Mac OS X is not Linux, and the GNU extensions don't necessarily work on non-Linux machines. The difficulty, sometimes, is determining when something is an extension. – Jonathan Leffler Jan 19 '14 at 21:21
  • BTW, `MM/DD/YYYY` is a very poorly chosen date format -- it's quite ambiguous with `DD/MM/YYYY`. Using `YYYY-MM-DD` sorts properly and is RFC-compliant. – Charles Duffy Mar 03 '17 at 16:58

3 Answers3

8

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.

chepner
  • 497,756
  • 71
  • 530
  • 681
3

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
yǝsʞǝla
  • 16,272
  • 2
  • 44
  • 65
  • there is nothing in between those lines. I actually an echo $? command right after, and it always prints 1 – Cbas Jan 19 '14 at 20:09
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 ...

fedorqui
  • 275,237
  • 103
  • 548
  • 598
deadElk
  • 31
  • 4