0

I'm trying to figure out how to detract days from a date, lets say I set the current date

set $date

How can I detract days from it and get the date of that period?

for example 27jul2012 detracting 5 becomes 22jul2012

Shahbaz
  • 46,337
  • 19
  • 116
  • 182
JBoy
  • 5,398
  • 13
  • 61
  • 101

4 Answers4

5

You can use date to calculate the difference, e.g.

date -d "27jul2012 - 5 days" +%d%b%Y
Lars Kotthoff
  • 107,425
  • 16
  • 204
  • 204
  • Hi, thx for the advice, and it is possible to asdsign this to a variable? i'm trying with: passato=date -d "27jul2012 - 90 days" +%Y%m%d but i'm not getting the value stored in the variable – JBoy Jul 23 '12 at 14:27
  • You need to assign the result of the execution rather than the command itself -- enclose the command in either backticks or `$()`. – Lars Kotthoff Jul 23 '12 at 14:34
1

Convert it to seconds first, subtract the number of seconds in five days and convert back:

date --date=@$(($(date --date='27 Jul 2012' +'%s') - $((5 * 24 * 3600)) )) +%x
fork0
  • 3,401
  • 23
  • 23
  • Not so useful for GNU date, which can do this sort of thing natively, but a good approach for other `date`s which can't, e.g. for FreeBSD: `date -j -f '%s' $(($(date -j -f '%d %h %Y' '27 Jul 2012' '+%s') - $((5 * 24 * 3600)) )) +%x` – sorpigal Jul 23 '12 at 14:32
  • @Sorpigal: Yep. I just upvoted the Larses answer for reminding me :) – fork0 Jul 23 '12 at 14:35
0

you can use the date utility to convert your date in second. see at Bash script compare two date variables.

and you can also perform several different kind of addition and subtraction from the current date. Have a look there : http://linuxconfig.org/addition-and-subtraction-arithmetics-with-linux-date-command

Community
  • 1
  • 1
A.G.
  • 1,279
  • 1
  • 11
  • 28
0

A slightly shorter version:

date --date="@$(expr $(date +%s) - 432000)"

Where 432000 is the number of seconds in 5 days.

Carnegie
  • 5,645
  • 2
  • 15
  • 7
  • It certainly works, but it requires an external calculation to know how many seconds are in 5 days and an extra process to do the math. `date` already handles both issues when parsing the argument to the `-d` option. – chepner Jul 23 '12 at 14:11
  • Indeed, I wasn't aware `date` could do that. Interesting! – Carnegie Jul 23 '12 at 14:26
  • Daylight savings means that not every day has 86400 seconds – glenn jackman Jul 23 '12 at 16:41