Bash 验证日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21221562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 09:17:44  来源:igfitidea点击:

Bash validate date

linuxbashmacosvalidationdate

提问by Cbas

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:

我正在编写一个 shell 脚本,对为什么我的日期验证代码不起作用感到困惑。我针对我发现的类似问题尝试了以下解决方案,但 is_valid 始终设置为 1:

date "+%m/%d/%Y" -d "" 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

如何正确验证日期格式?日期只有在格式为 MM/DD/YYYY 时才有效

I also tried this solution: Linux Bash - Date Formatbut it always rejected the date as well.

我也尝试过这个解决方案:Linux Bash - Date Format但它也总是拒绝日期。

回答by chepner

The BSD datethat ships with Mac OS X doesn't support the -doption (or rather, it uses -dfor something entirely different). Either install GNU date, or use the following to validate your input string:

dateMac OS X 附带的 BSD不支持该-d选项(或者更确切地说,它-d用于完全不同的东西)。要么安装 GNU date,要么使用以下内容来验证您的输入字符串:

date -f "%Y-%m-%d" -j "2012-02-29" >/dev/null 2>&1

The -fprovides the input format, and the -jtells dateto simply output the date, not attempt to set the system clock.

-f提供了输入格式,并-j讲述date简单地输出日期,不要试图设置系统时钟。

回答by y?s??la

I came up with this little function:

我想出了这个小功能:

function isDateInvalid()
{
  date -d "" "+%m/%d/%Y" > /dev/null 2>&1
  res=$?
  echo "$res"
}

isDateInvalid "2012-02-219"
1

isDateInvalid "2012-02-29"
0

回答by deadElk

for y in {2013..2014}; do
  for m in {01..12}; do
    for d in {01..31}; do
      [[ ! "`date -jf %Y%m%d $y$m$d +%Y%m%d`" = "$y$m$d" ]] && continue
      echo $y.$m.$d
    done
  done
done

if strings match, loop will proceed ...

如果字符串匹配,循环将继续......