Search code examples
bashdatetimestampcomparisonutc

How to compare two dates of different format?


Read from an ancient log, date is like this:

Wed 31 Oct 2018 08:42:00 AM UTC

The other date is like this:

12-10-2018 14:37:42

which was the best I could get with date -r ${fname} "+%m-%d-%Y %H:%M:%S".

Is it possible to compare these dates? The fact that first uses a word for the day discourages me severely. If yes, how?


Solution

  • If you're getting dates in above format, then you need to convert 2nd data string to make it parseable by Unix date command first. Here is an example:

    #!/usr/bin/env bash
    
    dt1='Wed 31 Oct 2018 08:42:00 AM UTC'
    dt2='12-10-2018 14:37:42'
    
    dt2=$(sed -E 's/^([0-9]{2}-[0-9]{2})-([0-9]{4})/\2-\1/' <<< "$dt2")
    echo "$dt2" # 2018-12-10 14:37:42
    
    # compare EPOCH second values of both dates
    
    if (( $(date -d "$dt1" '+%s') < $(date -d "$dt2" '+%s') )); then
        echo "date1 is less than date2"
    else
        echo "date1 is >= than date2"
    fi