Bash (Shell) Script To Compare Date And Time

I come across the need to compare the time and date in shell.

Here is how I did.

Convert the time to seconds

First we convert times into seconds and then compare them.

date is a command to get the current time and date,

you can specify the output format by appending +FORMAT option,

and specify the time not now by appending -d STRING option

For example:

date -d '2012-12-21 00:00:00` +%s

Compare seconds

Below is the script:

    doomsday=`date -d "2012-12-21" +%s`
    today=`date +%Y-%m-%d`
    today=`date -d $today +%s`

    if [ $doomsday -gt $today ]; then
        echo The world may end on December 21 2012.
    elif [ $doomsday -eq $today ]; then
        echo Today is the doomsday. What is happening now?
        echo Congratulations! The world did not end on December 21 2012.