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.

5
  • I'm not experiencing the same result. When I run date -d "2012-02-29 > /dev/null 2>&1" then "echo $?" I get 0`. Commented Jan 19, 2014 at 19:45
  • What does date --version print for you? (BTW, I get the same result as mbratch and Aleksey Izmailov.) Commented Jan 19, 2014 at 19:54
  • It prints: "date: illegal option -- - \n usage: date ....." I'm using Mac OSX btw Commented Jan 19, 2014 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. Commented Jan 19, 2014 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. Commented Mar 3, 2017 at 16:58

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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 

1 Comment

there is nothing in between those lines. I actually an echo $? command right after, and it always prints 1
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 ...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.