Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

326
Views
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.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report

0

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
over 4 years ago · Santiago Trujillo Report

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!