5

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 !

2
  • why not string operation ? Commented Mar 27, 2015 at 22:12
  • I tried [ var1 > var2 ] but it turns true every time Commented Mar 27, 2015 at 22:17

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

Comments

7

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.