17

I have a date string that I am able to parse and format with the date command from a bash script.

But how can I determine how many days ago this date was from my script? I would like to end up with a number.

D Stanley
  • 149,601
  • 11
  • 178
  • 240
Dennis Thrysøe
  • 1,791
  • 4
  • 19
  • 31

3 Answers3

11

Use date itself as date value for date. Example 5 days ago:

date -d "`date`-5days"
Andreas WP
  • 127
  • 1
  • 2
9

You can do some date arithmetics:

DATE=01/02/2010
echo $(( ( $(date +%s) - $(date -d "$DATE" +%s) ) /(24 * 60 * 60 ) ))
marco
  • 4,455
  • 1
  • 23
  • 20
  • 2
    Its worth mentioning here that the version of date on AIX doesn't have a -d option, so although the OP was asking for a Linux solution, this would not be a cross-platform solution. – frankster Nov 19 '12 at 15:21
  • 2
    On OSX the man pages say: `-d dst Set the kernel's value for daylight saving time.` – andsens Apr 13 '13 at 17:41
4

Convert your date and now into seconds since the epoch, subtract, divide by the number of seconds in a day:

#!/bin/bash

((a = `date -d "Wed Jan 12 02:33:22 PST 2011" +%s`))
((b = `date +%s`))
echo $(( (b-a) / (60*60*24)))
sarnold
  • 102,305
  • 22
  • 181
  • 238
  • 5
    On a side note, you can do relative dates in `date` directly: `date --date="2011-01-13+5days"` – l0b0 Jan 13 '11 at 11:41
  • Neat! :) Thanks. But that is only helpful if you are aiming at a specific number of days different from a given date, not finding the difference between two given dates. – sarnold Jan 13 '11 at 11:44
  • 1
    It's not necessary to do a simple assignment inside double parentheses (you wouldn't be able to have spaces around the equal sign, however). You should, however, use `$()` for command substitution instead of using backticks. – Dennis Williamson Jan 13 '11 at 15:30