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
    Commented 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 Commented 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 Commented May 11, 2021 at 16:04
  • @daturmgirl single quotes prevent variable expansion Commented May 11, 2021 at 16:36
  • Related - unix.stackexchange.com/q/193070/100397 Commented 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
    Commented May 12, 2021 at 9:10

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.