Ruby年 - 月 - 上周日的日期

时间:2014-01-27 23:02:47

标签: ruby-on-rails ruby time

我需要以最后两个星期日2014-01-20的格式计算。

所以,last_sunday = 2014-01-20most_recent_sunday = 2014-01-26

我正在使用Rails 4.0和Ruby 2.0。我怎样才能得到这些日期?

4 个答案:

答案 0 :(得分:6)

在rails 4中:

most_recent_sunday = Time.now.sunday.to_s

last_sunday =        Time.now.last_week.sunday.to_s

要使其符合您的格式:

DateTime.parse(most_recent_sunday).strftime("%Y-%m-%d")

http://apidock.com/rails/v4.0.2/DateAndTime/Calculations/sunday http://apidock.com/rails/v4.0.2/DateAndTime/Calculations/last_week

答案 1 :(得分:1)

我建议你看看chronic gem

require 'chronic'
Chronic.parse("last sunday")
=> 2014-01-26 12:00:00 +0200

您还可以使用rail的active_support从上面计算的日期中减去7.days =)

答案 2 :(得分:0)

[11] pry(main)> last_sunday = Time.now - (Time.now.wday + 7) * 86400
=> 2014-01-19 17:17:19 -0600
[12] pry(main)> most_recent_sunday = Time.now - (Time.now.wday) * 86400
=> 2014-01-26 17:18:03 -0600

答案 3 :(得分:0)

纯Ruby解决方案:

require 'date'

last_two_weeks   = (Date.today-13)..Date.today
last_two_sundays = last_two_weeks.select &:sunday?

puts last_two_sundays #=> 2014-01-19, 2014-01-26