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
muru
  • 72,889

2 Answers2

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
glenn jackman
  • 85,964
-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