简体   繁体   English

Unix日期格式验证

[英]Unix date format validation

I wrote this small Unix shell script to validate the date format. 我写了这个小的Unix shell脚本来验证日期格式。 My script should check whether the string is in YYYYMMDDHHMMSS format. 我的脚本应检查字符串是否为YYYYMMDDHHMMSS格式。 If it is not in this format, it should send an error message. 如果不是这种格式,则应发送错误消息。

For example, I declared an variable a and assigned a value to it. 例如,我声明了一个变量a并为其分配了一个值。

a=20150620223405
date "+%Y%m%d%H%M%S" -d $a > /dev/null 2>&1
if [ $? -ne 0 ]
then
  echo "Invalid format"
else
  echo "Valid format"
fi 

It always shows as "Invalid format", I want to know what is the mistake here and how to proceed. 它始终显示为“无效格式”,我想知道这里的错误是什么以及如何处理。

From man date : man date

DATE STRING 日期STRING

The --date=STRING is a mostly free format human readable date string such as "Sun, 29 Feb 2004 16:21:42 -0800" or "2004-02-29 16:21:42" or even "next Thursday". --date = STRING是一种大多数形式的人类可读日期字符串,例如“ Sun,2004年2月29日16:21:42 -0800”或“ 2004-02-29 16:21:42”,甚至是“下一个星期四” 。 A date string may contain items indicating cal‐ endar date, time of day, time zone, day of week, relative time, rela‐ tive date, and numbers. 日期字符串可能包含指示日历日期,一天中的时间,时区,星期几,相对时间,相对日期和数字的项目。 An empty string indicates the beginning of the day. 空字符串表示一天的开始。 The date string format is more complex than is easily documented here but is fully described in the info documentation. 日期字符串格式比这里容易记录的要复杂,但是在信息文档中有完整的描述。

And about format: 关于格式:

FORMAT controls the output. FORMAT控制输出。

This means that you cannot validate the date you pass as an argument. 这意味着您无法验证作为参数传递的日期。 date validates it by itself regardless of format you supplied (as man says that FORMAT controls the output, not the input). date本身会对其进行验证,而与您提供的格式无关(就像男人说的那样,FORMAT控制输出,而不是输入)。

To validate the date i'd suggest you to use a regular expression and grep (1) . 为了验证日期,我建议您使用正则表达式和grep (1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM