Rails - 获取当前周和月的开始和结束日期

时间:2022-09-26 11:13:49

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:

我是铁杆上的红宝石新手,被困在日期里。我用Time.now来获取当前时间。现在我想找出当前周和当月的srart和结束日期。例如:

If Time.now returns me -

如果Time.now还给我 -

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

等等..但我发现这不是一个方便的方法。我确信Ruby on Rails确实拥有更好的解决方案。任何人都可以建议弄清楚相同..

2 个解决方案

#1


54  

Instead of using Time.now

而不是使用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

同样,您可以在Date类中找到多个方法

#2


2  

Check out the Date class:

查看Date类:

http://api.rubyonrails.org/classes/Date.html

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.

begin_of_ *和end_of_ *方法看起来就像你正在追求的那样。对于本周,您甚至可以在考虑本周开始的那一天通过。

#1


54  

Instead of using Time.now

而不是使用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

同样,您可以在Date类中找到多个方法

#2


2  

Check out the Date class:

查看Date类:

http://api.rubyonrails.org/classes/Date.html

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.

begin_of_ *和end_of_ *方法看起来就像你正在追求的那样。对于本周,您甚至可以在考虑本周开始的那一天通过。