hbelmiro
hbelmiro

Reputation: 1027

Comparing dates in a specific format

I have to compare (greater than) two dates formatted as 'dd/MM/yyyy hh:mm:ss'. For instance: 30/11/2015 14:24:35. I've tried to convert them to timestamp and then compare each other. But the attempt to convert to timestamp wasn't successful.

$ date --date='16/12/2012 07:21:22' +"%s"
date: invalid date `16/12/2012 07:21:22'

How can I do that (directly, or converting to timestamp, or using another solution)?

Upvotes: 0

Views: 239

Answers (1)

Toby Speight
Toby Speight

Reputation: 30992

You will want to re-order the fields.

For example, with sed and bash:

date="$(sed -re 's_(..)/(..)/(....) _\3-\2-\1 _' <<<"$date")"

Once you have them in big-endian form, you can do the comparison lexically - there's no longer any need to convert to epoch seconds. According to the Bash man page, its built-in test (but not /usr/bin/test) can compare strings with '<' and '>'. Remember that they need quotes, so as not to be misinterpreted as redirections!

Upvotes: 2

Related Questions