Quick Date Calculations With Date

By eric

I frequently find myself needing to do quick date calculations in order to make scripts run when I want them to or how I want them to. Usually Date::Calc is just a bit too heavily, especially if it’s something as simple as a BASH script. As it happens, date is quite a powerful tool for some command line fu.

For example, to find the first and last day of last month:

1
2
FIRST_DOLM=`date -d "-1 month -$(($(date +%d)-1)) days" "+%Y-%m-%d"`
LAST_DOLM=`date -d "-$(date +%d) days" "+%Y-%m-%d"`

You can do the same thing using the date command on a mac with a slightly different set of switches:

1
2
FIRST_DOLM=`/bin/date -v1d -v-1m "+%Y-%m-%d"`
LAST_DOLM=`/bin/date -v31d -v-1m "+%Y-%m-%d"`

Both of these will produce the same results:

1
2
2009-06-01
2009-06-30

Follow My Travels

Buy My Book

Archives

  • 2014
  • 2013
  • 2012
  • 2011
  • 2010
  • 2009
  • 2008
  • 2007
  • 2006

writing