nocturne
nocturne

Reputation: 647

Compare two dates in shell script

I need to compare two dates which are stored in two variables, the format is YYYY-MM-DD . I suppose I can store them in another variables and use some tr -d "-",then compare like integers, but I don’t know how. Thanks in advance !

Upvotes: 5

Views: 21933

Answers (2)

glenn jackman
glenn jackman

Reputation: 247240

You may need to call out to expr, depending on your mystery shell:

d1="2015-03-31" d2="2015-04-01"
if [ "$d1" = "$d2" ]; then
    echo "same day"
elif expr "$d1" "<" "$d2" >/dev/null; then
    echo "d1 is earlier than d2"
else
    echo "d1 is later than d2"
fi
d1 is earlier than d2

The test command (or it's alias [) only implements string equality and inequality operators. When you give the (non-bash) shell this command:

[ "$d1" > "$d2" ]

the > "$d2" part is treated as stdout redirection. A zero-length file named (in this case) "2015-04-01" is created, and the conditional command becomes

[ "$d1" ]

and as the variable is non-empty, that evaluates to a success status.

The file is zero size because the [ command generates no standard output.

Upvotes: 10

Abhay
Abhay

Reputation: 768

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". Once you get that it's really easy to do almost anything with dates. And there are a couple of options to convert a number back to date too.

Upvotes: 7

Related Questions