Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - Get the current week's and month's start and end dates

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..

like image 846
Swati Aggarwal Avatar asked Aug 13 '12 10:08

Swati Aggarwal


2 Answers

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

like image 179
Shreyas Agarwal Avatar answered Nov 18 '22 10:11

Shreyas Agarwal


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.

like image 20
Nick Avatar answered Nov 18 '22 10:11

Nick