Reputation: 133
i want to check if Date is valid or not using Script shell.
I tried this:
date "+%d/%m/%Y" -d "09/10/2013" > /dev/null 2>&1
is_valid=$?
It works fine for me when it comes to dd/MM/YYYY format. I Tried
date "+%Y%m%d%H%M%S" -d "20191001041253" > /dev/null 2>&1
is_valid=$?
for YYYYmmddHHMMSS but it doesn't work.
Could someone please guide me to check if a date is valid or not with the YYYYmmddHHMMSS.
Upvotes: 1
Views: 6302
Reputation: 14422
The 'date' utility accept date values in many formats (look at info date, 'Date Input formats' section). The bad news is that the format you need ( 'YYYYmmddHHMMSS') is not supported. The good news is that similar format (ISO compact format 'YYYYmmdd< HH:MM:SS') is supported.
date -d '20191001 05:06:07'
Tue Oct 1 05:06:07 IDT 2019
If you want to LIMIT the input date format to accept ONLY YYYYmmddHHMMSS, you actually have to write a small filter
input=20191001050607
# Convert to YYYYmmdd HH:MM:SS
t="${input:0:8} ${input:8:2}:${input:10:2}:${input:12:2}"
is_valid=
# Validate; Check for 14 digits + try to convert to date
[[ "$input" =~ ^[0-9]{14}$ ]] && date -d "$t" > /dev/null 2>&1 && is_valid=YES
echo "$is_valid"
Upvotes: 1
Reputation: 140890
GNU date has a very relaxed syntax as to how to read input. The "+..."
is only for specifying the output of it, you cannot in any way specify how should it read/parse the input.
You need to first convert your input into something GNU date can understand. I found that the format mentioned in the DATE STRING
section in man page seems to be most reliable.
s=20191001041253
# 2019-10-01 04:12:53
s="${s::4}-${s:4:2}-${s:6:2} ${s:8:2}:${s:10:2}:${s:12:2}"
if date --date="$s" >/dev/null 2>/dev/null; then
echo "Its ok"
else
echo "its invalid"
fi
Note that bsd date has an -f
options that allows specifying input format. I wish such option would be available with gnu date.
Upvotes: 1
Reputation: 445
Try changing it to ISO
format:-
$ date "+%Y%m%d%H%M%S" -d "2019-10-01 04:12:53"
20191001041253
$ echo $?
0
Upvotes: 1