Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...