I want to use the cal command or the date command to display the current day, then I want it to display 3 months before the current date, then add up all the days in those 3 months up to the current day. Is there a way to do this?

So today's date is displayed as:

Fri Dec 19 13:23:36 GMT 2014 

3 months ago would be:

Fri Sep 19 13:23:36 GMT 2014 

I want all the days added up by Linux from September 19th to December 19th, then display the result of that calculation.

  • What should the result be on the 31st of May? – Stéphane Chazelas Dec 19 '14 at 14:55
  • 28 th February as it is the last day of the month and the 31st of May is the last day of the month this was a good question – user2995836 Dec 19 '14 at 14:58

bash and GNU date

#grab today's date in YYYYMMDD format
today=$(date +%Y%m%d)
#grab date as of 3 months ago in YYYYMMDD format
three_months_ago=$(date +%Y%m%d --date='3 months ago')

#now convert dates to "seconds since epoch" format, and then divide the difference  by 60*60*24 to convert from seconds to days
printf '%d\n' $(( ($(date --date=$today +%s) - \
  $(date --date=$three_months_ago +%s))/(60*60*24) ))
  • thank you can you just give me a quick explanation please it looks a bit confusing – user2995836 Dec 19 '14 at 14:48
  • @user2995836, see if the comments help – iruvar Dec 19 '14 at 15:09
  • For GNU date, 3 months ago on 2014-05-31 is 2014-03-03. You'll also be off by one day when across one of the DST shifts in timezones where they apply. For instance, there are 89 days between 2014-02-21 and 2014-05-21, but your solution would report 88 in most timezones that change their clock for daylight saving. – Stéphane Chazelas Dec 19 '14 at 15:24
  • Note that that syntax is zsh, not bash. In bash, you need to quote variables and arithmetic expansions. – Stéphane Chazelas Dec 19 '14 at 15:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.