Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

For MongoDB backups, I want to backup only the newest changes from the previous month instead of everything from the previous month. As part of the query I need to pass to "mongodump", I have to determine the first day/last month and the last day/last month, which I've done as follows:

date -d "-1 month -$(($(date +%d)-1)) days"
Sat Dec  1 21:05:21 UTC 2012

date -d "-$(date +%d) days -0 month" 
Mon Dec 31 21:06:22 UTC 2012

As you can see this almost works, but the time portion of the above 'date' examples reflect the current time relative to my timezone. In order for only the newest backup data from the previous month to be 100% inclusive, I need to specify the timestamp portion for the first and last day of the previous month to instead be displayed as follows:

Sat Dec  1 00:00:00 UTC 2012
Mon Dec 31 23:59:59 UTC 2012

Is there a way to display the time portion of the date/time in the manner listed above?

share|improve this question

You're on the right track, but instead of computing a time difference, build an absolute date corresponding to the first of this month. Set the TZ environment variable to operate in a different timezone.

TZ=UTC date -d "$(date +%Y-%m-01) -1 month"
TZ=UTC date +%Y-%m-01
share|improve this answer

Does this work for you?

date -d "-1 month -$(($(date +%d)-1)) days" "+%a %b %d 00:00:00 %Z %Y"
date -d "-$(date +%d) days -0 month" "+%a %b %d 23:59:59 %Z %Y"
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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