Quick Date Calculations With Date

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:

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:

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:

2009-06-01
2009-06-30
Be a loud mouth:
  • Digg
  • Twitter
  • del.icio.us
  • Google Bookmarks
  • Facebook
  • email
  • Ping.fm
  • Reddit
  • Technorati

No related posts.

View Comments to “Quick Date Calculations With Date”


Trackbacks/Pingbacks

  1. [...] View original post here:  Quick Date Calculations With Date [...]

Leave a Reply

blog comments powered by Disqus