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?


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
| 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"
| improve this answer | |

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.