tags:

views:

35

answers:

3

How can I get a Time object corresponding to the start of the current calendar month? E.g., if I ran the function today I'd get a Time object for 7/1/2010 at midnight

Bonus question: How can I do the same thing for the current week? If I ran this function today I'd get a Time object for 7/11/2010 at midnight

+3  A: 
 Date.civil(Date.today.year, Date.today.month, 1)

Bonus, to get the Sunday:

Date.commercial(Date.today.year, Date.today.cweek - 1, 7)

To get the Monday

Date.commercial(Date.today.year, Date.today.cweek, 1)

Resources: http://ruby-doc.org/core/classes/Date.html

Edit: I changed my mind on the Sunday, you would have issues at the beginning of a year. So I would do this instead to get sunday

Date.commercial(Date.today.year, Date.today.cweek, 1) - 1
Geoff Lanotte
A: 

Try this:

Time.utc(Time.new.year,Time.new.month)

Also see Time.gm, Time.local (whatever you require)

xagyg
+1  A: 

Rails' ActiveSupport has helpers for all such things (beginning_of_month, beginning_of_week, etc.)

Andrew Vit