I need to compare two dates/times using Bash.
Input format: 2014-12-01T21:34:03+02:00
I want to convert this format to int
and then compare the int
s of the two dates.
Or does bash have another way to compare two dates?
You can use date +%s -d your_date to get the number of seconds since a fixed instance (1970-01-01, 00:00 UTC) called "epoch".
== is a bash-specific alias for = and it performs a string (lexical) comparison instead of a numeric comparison. eq being a numeric comparison of course.
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" ]]
From the man:
[[ 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With