0

i am writing a generic script for the custom format date validation . here is the script

dateformat=$1
d=$2
date "+$dateformat" -d "$d" > /dev/null  2>&1
if [ $? != 0 ]
then
    echo "Date $d NOT a valid YYYY-MM-DD date"
    exit 1
fi

issue is

  • sh -x poc_col_val_date.sh "%Y-%m-%d" "2019-11-09" expected is valid date, output also correct
  • sh -x poc_col_val_date.sh "%d-%m-%Y" "2019-11-09" expected is invalid date, output is valid date
6
  • 1
    The + format string sets the output format. It doesn't affect input parsing.
    – muru
    May 11, 2021 at 15:19
  • ... the busybox implementation can do it I think, via its -D option ex. busybox date -D "%d-%m-%Y" -d "2019-11-09" ==> date: invalid date '2019-11-09' and an exit status of 1 May 11, 2021 at 15:35
  • is there any issue in the code . Busybox is getting me both inputs are invalid.dateformat=$1 d=$2 busybox date -d '$2' -D '$dateformat' > /dev/null 2>&1 if [ $? != 0 ] then echo "Date $d NOT a valid YYYY-MM-DD date" exit 1 fi May 11, 2021 at 16:04
  • @daturmgirl single quotes prevent variable expansion May 11, 2021 at 16:36
  • Related - unix.stackexchange.com/q/193070/100397 May 11, 2021 at 16:55

2 Answers 2

2

You could use perl here. This uses Time::Piece which is a core module.

valid_date() {
  # this function returns with the exit status of the perl command
  perl -MTime::Piece -se 'Time::Piece->strptime($date, $fmt)' -- -fmt="$1" -date="$2" 2>/dev/null
}

So

valid_date '%Y-%m-%d' '2019-11-09' && echo Y || echo N     # => Y
valid_date '%d/%m/%y' '2019-11-09' && echo Y || echo N     # => N
-4

I tested with below script you will come to know about valid and invalid date

#!/bin/bash
d="2021-03-20"
z="20-03-2021"
date +%Y-%m-%d -d "$d"
if [ $? -eq 0 ]
then
echo "its valid date"
fi
echo "========================="

date +%d-%m-%Y -d "$d"
if [ $? -eq 0 ]
then
echo "its valid date"
fi

echo "========================"

date +%Y-%m-%d -d "$z"
if [ $? -ne 0 ]
then
echo "its not a valid date"
fi




output

2021-03-20
its valid date
=========================
20-03-2021
its valid date
========================
date: invalid date ‘20-03-2021’
its not a valid date
1
  • 1
    Why didn't you test "$z" with +%d-%m-%Y?
    – muru
    May 12, 2021 at 9:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .