Date comparison in Bash

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

One option would be to convert the date to the number of seconds since the UNIX epoch:

date -d "2014-12-01T21:34:03+02:00" +%s

You can then compare this integer to another date which has been processed in the same way:

(( $(date -d "2014-12-01T21:34:03+02:00" +%s) < $(date -d "2014-12-01T21:35:03+02:00" +%s) ))

The (( )) syntax is used to create an arithmetic context as we are comparing two numbers. You could also use the more general [ ${x} -lt ${y} ] style syntax if portability is a concern.

One advantage of doing it this way is that date understands a variety of formats, for example
date -d "next year" +%s. Furthermore, date understands timezones, so it can correctly handle comparisons between pairs of dates where the timezone is different.

However, if neither of those issues concerns you, then I'd go for j.a.'s solution.

Tags:

Linux

Bash

Date