Bash中的日期比较 [英] Date comparison in Bash
问题描述
我需要使用Bash比较两个日期/时间。
I need to compare two dates/times using Bash.
输入格式:2014-12-01T21:34:03 + 02:00
Input format: 2014-12-01T21:34:03+02:00
我想将此格式转换为 int
,然后比较 int
I want to convert this format to int
and then compare the int
s of the two dates.
或者bash有另一种方式来比较两个日期?
Or does bash have another way to compare two dates?
推荐答案
You can compare lexicographically with the conditional construct [[ ]]
in this way:
[[ "2014-12-01T21:34:03+02:00" < "2014-12-01T21:35:03+02:00" ]]
从男人:
[[expression]]
根据条件表达式表达式的评估返回0或1的状态。
[[ expression ]]
Return a status of 0 or 1 depending on the evaluation of the conditional expression expression.
新更新:
New update:
如果您需要比较不同时区的时间,可以先转换这些时间:
If you need to compare times with different time-zone, you can first convert those times in this way:
get_date() {
date --utc --date="$1" +"%Y-%m-%d %H:%M:%S"
}
$ get_date "2014-12-01T14:00:00+00:00"
2014-12-01 14:00:00
$ get_date "2014-12-01T12:00:00-05:00"
2014-12-01 17:00:00
$ [[ $(get_date "2014-12-01T14:00:00+00:00") < $(get_date "2014-12-01T12:00:00-05:00") ]] && echo it works
it works
这篇关于Bash中的日期比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!