如何根据当前星期红宝石中的日期获得上周的开始日期和结束日期

时间:2015-02-04 11:05:51

标签: ruby

如何根据当前星期红宝石(星期一至星期日)的日期获取上周的开始日期和结束日期

示例:如果日期为04-feb-15,则结果应为start_date = Monday(26-jan-1015)end_date = Sunday(1-feb-15)

如果日期是27-feb-15,那么结果应该是start_date = Monday(16-feb-1015)end_date =(22-feb-15)

5 个答案:

答案 0 :(得分:2)

您可以尝试这种方式:

require 'date'
=> true

date = Date.today
=> #<Date: 2015-02-04 ((2457058j,0s,0n),+0s,2299161j)>

# date.wday return week day
end_date = date-date.wday
=> #<Date: 2015-02-01 ((2457055j,0s,0n),+0s,2299161j)>

start_date = date-date.wday-6
=> #<Date: 2015-01-26 ((2457049j,0s,0n),+0s,2299161j)>

有关更多操作,请参阅此链接Ruby Doc.

答案 1 :(得分:0)

使用日期#wday告诉一周中的某一天是给定日期,然后相应地减去:

require 'date'

date = Date.parse("15-02-04")
monday = date - (date.wday + 6) # 2015-01-26
sunday = date - date.wday # 2015-02-01

date = Date.parse("15-02-27")
monday = date - (date.wday + 6) # 2015-02-16
sunday = date - date.wday # 2015-02-22

答案 2 :(得分:0)

我已经尝试过以下代码,工作正常。

monday = (Date.today.beginning_of_week - 7) # 2015-01-26
sunday = (Date.today.end_of_week - 7) # 2015-02-01

答案 3 :(得分:0)

您可以尝试这种方式

monday = (Date.today.beginning_of_week.last_week)

sunday = (Date.today.beginning_of_week.last_week + 7)

答案 4 :(得分:0)

  • 上周的第一天

     Date.today.last_week.beginning_of_week
    
  • 上周的最后日期

     Date.today.last_week.at_end_of_week