Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date comparison in Bash [duplicate]

Tags:

date

linux

bash

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 ints of the two dates.

Or does bash have another way to compare two dates?

like image 502
Андрей Сердюк Avatar asked Dec 11 '14 18:12

Андрей Сердюк


People also ask

How do I compare two dates in shell?

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 == used in bash?

== 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.


1 Answers

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
like image 106
whoan Avatar answered Oct 24 '22 09:10

whoan