I am new to ruby on rails and got stuck in dates. I used Time.now
to get the current time. Now I want to find out the srart and end dates for the current week and current month. For instance:
If Time.now
returns me -
2012-08-13 15:25:35 +0530
Then the start and end dates for the current week are:
2012-08-12 - 2012-08-18
Then the start and end dates for the current month are:
2012--08-01 - 2012-08-31
I am implementing the same using the code:
Time.now.wday
=> 1
Time.now - 1.day
=> 2012-08-12 15:31:44 +0530
Time.now + 5.day
=> 2012-08-19 15:32:38 +0530
and so on.. But I dont find it a convenient way to do this. Iam sure Ruby on Rails does hold a better solution. Can anyone suggest to figure out the same..
Instead of using Time.now
Use the following code to get your queries solved
d = Date.today
d.at_beginning_of_week
#Mon, 13 Aug 2012
d.at_beginning_of_week.strftime
#"2012-08-13"
d.at_beginning_of_week.strftime("%d")
#"13" -> To print the date.
Similarly you can find multiple methods in the Date Class
Check out the Date class:
http://api.rubyonrails.org/classes/Date.html
The methods beginning_of_* and end_of_* look like exactly what you're after. For the week, you can even pass in what day you consider the start of the week.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With