Ruby-on-rails Rails - 获取当前周和月的开始和结束日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11932091/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails - Get the current week's and month's start and end dates
提问by Swati Aggarwal
I am new to ruby on rails and got stuck in dates. I used Time.nowto get the current time. Now I want to find out the srart and end dates for the current week and current month. For instance:
我是 ruby on rails 的新手并且陷入了约会。我曾经Time.now得到当前时间。现在我想找出当前周和当前月的 srart 和结束日期。例如:
If Time.nowreturns 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 确实拥有更好的解决方案。任何人都可以建议找出相同的..
回答by Shreyas Agarwal
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 类中找到多个方法
回答by Nick
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_* 看起来正是你想要的。对于一周,您甚至可以传入您认为一周开始的哪一天。

