Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

yyyymmddが正しい日付かチェックする

More than 1 year has passed since last update.

日付の文字列が正しいか判断するのに正規表現を使った複雑な比較もあるが、dateコマンドを使うのが一番楽かな。。。

$ date +%Y%m%d -d 20190230
date: '20190230' は無効な日付です
$ date +%Y%m%d -d 20190229
date: `20190229' は無効な日付です
$ date +%Y%m%d -d 20200229
20200229
$ date +%Y%m%d -d abcd
date: `abcd' は無効な日付です

元のyyyymmddとdateコマンドを通した後のyyyymmddを比較して一致してたら正しい日付

A=20200218
B=$(date +%Y%m%d -d $A 2>/dev/null)
if [ "$A" = "$B" ]; then
    echo "correct date"
else
    echo "incorrect date"
fi
baoh0308
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away