我看不到任何方法来指定日期
的解析格式,并且我的输入格式无法识别:
dt1=`date --date="20151020T113100.475"`; echo $dt1 # fails with 'invalid date'
最佳答案
根据 DevSolar 的建议,如果您没有使用这些值进行任何其他日期处理,则可以使用
if [[ $dt1 < $dt2 ]]; then
# your logic here..
printf "less than..\n";
else
# your logic here..
printf "greater than or equal..\n";
fi
如果您需要将这些转换为日期形式和/或想要验证字符串输入,可以使用 bash 子字符串提取:
$ dt1="20151020T113100.475"
$ date -d "${dt1:0:4}-${dt1:4:2}-${dt1:6:2} ${dt1:9:2}:${dt1:11:2}:${dt1:13:6}"
Tue Oct 20 11:31:00 AEDT 2015
输出格式也可以在这里应用,例如:
$ date -d "${dt1:0:4}-${dt1:4:2}-${dt1:6:2} ${dt1:9:2}:${dt1:11:2}:${dt1:13:6}" +"%s"
1445301060
此处 %s 给出自 1970-01-01 00:00:00 UTC 以来的秒数
因此,要与另一个日期(dt2
)进行比较,可以使用类似的内容
dt1="20151020T113100.475"
dt2="20151021T113100.475"
ts1=$(date -d "${dt1:0:4}-${dt1:4:2}-${dt1:6:2} ${dt1:9:2}:${dt1:11:2}:${dt1:13:6}" +"%s")
ts2=$(date -d "${dt2:0:4}-${dt2:4:2}-${dt2:6:2} ${dt2:9:2}:${dt2:11:2}:${dt2:13:6}" +"%s")
if ((ts1<ts2)); then
# your logic here..
printf "less than..\n"
else
# your logic here..
printf "greater than or equal..\n"
fi
输出
less than..
参见man date 有效的输出格式
关于linux - 如何将字符串转换为特定格式的日期时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33236050/