Linux的巴什 - 日期格式 [英] Linux Bash - Date Format
问题描述
我的日期格式为YYYY-MM-DD-HH:MM:SS
如何检查我的投入?
My date format is yyyy-mm-dd-hh:mm:ss How do I check my input?
应该是这样的:
#!/bin/bash
read -p "Date (format yy-mm-dd-HH-MM-SS): " input
check=$(date +"%Y-%m-%d-%H:%M:%S")
if [ $input -eq $check ]; do
echo "Right!"
else
echo "False!"
fi
但是,这并不检查日期是我比较投入与实际日期。
But that doesn't check the date It compares my input with the real date.
祝商祺
文斯
推荐答案
另见(更强的方法)
尝试:
#!/bin/bash
read -p "Date (format yyyy-mm-dd): " input
check=$(date +%F)
if [ "$input" == "$check" ]; then
echo "Right!"
else
echo "False!"
fi
或
#!/bin/bash
read -p "Date (format YYYY-MN-DD-HH24:MM:SS): " input
check=$(date +%F-%T)
if [ "$input" == "$check" ]; then
echo "Right!"
else
echo "False!"
fi
很好的测试:
cat >hesdate.sh # Copy 1st sample and paste to terminal
chmod +x hesdate.sh
date +%F ; ./hesdate.sh
2013-01-04
Date (format yyyy-mm-dd): 2013-01-04
Right!
cat >hesdate.sh # Copy 2nd sample and paste to terminal
date -d now\ +10\ sec +%F-%T ; ./hesdate.sh
2013-01-04-10:17:06 # copy this line
Date (format YYYY-MN-DD-HH24:MM:SS): 2013-01-04-10:17:06 # past exactly 10 secs after
Right!
修改添加
有关测试的日期,你可以:
For testing a date, you could:
[[ $input =~ ^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]$ ]]
if [[ $input =~ ^2012-[0-9][0-9]-[0-9][0-9]-[0-9][0-9]:[0-9][0-9]:[0-9][0-9]$ ]];then
和/或
inputSecs=$(date -d "${input%-*} ${input##*-}" +%s)
使用引导方法,让您确认的格式的和 输入可靠性的
如果您要检查输入,还有一个更精细的方式:
If you want to check input, there is a finer method:
unset adate
declare -A adate
date=2013-12-04-10:17:06
for field in s:0-59 m:0-59 h-0-23 D-1-31 M-1-12 Y#2000-2100 ;do
sep=${field:1:1} min=${field:2} field=${field:0:1} max=${min#*-} min=${min%-*}
crt=${date##*${sep:-#}}
((min<=10#$crt&&10#$crt<=max)) && adate[$field]=$crt ||
echo Error: $crt not between $min and $max in $field field.
date=${date%$sep*}
done
declare -p adate
这将转储 ADATE
数组变量:
declare -A adate='([D]="04" [M]="12" [Y]="2013" [h]="10" [m]="17" [s]="06" )'
从那里,你可以重新验证的天数的:
max=$(date -d "${adate[Y]}-${adate[M]}-1 +1 month -1 day" +%d)
((10#${adate[D]}>max)) && echo "Error Day number too high: (${adate[D]}>$max)."
唯一没有测试有字段长度,如果
The only thing not tested there is field length if
date=2012-02-29-10:17:06
将工作,然后
date=2012-2-29-10:17:06
将工作过(只有一个在一天的实地位)。
will work too (there is only one digit in day field).
如果需要,你可以改变行:
If needed, you could change the line:
for field in s:0-59 m:0-59 h-0-23 D-1-31 M-1-12 Y#2000-2100 ;do
sep=${field:1:1} min=${field:2} field=${field:0:1} max=${min#*-} min=${min%-*}
crt=${date##*${sep:-#}}
为
for field in s:20-59 m:20-59 h-20-23 D-21-31 M-21-12 Y#42000-2100 ;do
sep=${field:1:1} len=${field:2:1} min=${field:3} field=${field:0:1} max=${min#*-} min=${min%-*}
crt=${date##*${sep:-#}}
[ ${#crt} -eq $len ] || echo "Error: Field $field is no $len len: ${#crt}."
诺塔:新年场2000和2100之间的任意限制,但是这是很容易理解/更改
Nota: Year field is arbitrarily limited between 2000 and 2100, but this is easy to understand/change.
这篇关于Linux的巴什 - 日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!