查找给定周数的日期

时间:2012-03-05 22:19:45

标签: ruby date

我正在尝试根据给定年份的周数来做一些日期数学。例如:

date = Date.today # Monday, March 5, 2012
puts date.cwyear  # 2012
puts date.cweek   # 10 (10th week of 2012)

现在我知道当前的一周是什么,我想知道下周和上周是什么。我需要将年份(2012)和周数(10)转回日期对象,以便我可以计算下一周/前一周的值。我怎么能这样做?

5 个答案:

答案 0 :(得分:15)

您想要Date.commercial

require 'date'
now = Date.today                                           #=> 2012-03-05
monday_next_week = Date.commercial(now.cwyear,now.cweek+1) #=> 2012-03-12
next_sunday_or_today = monday_next_week - 1                #=> 2012-03-11

请注意,星期一星期开始,所以如果你在星期天并要求下一个星期一 - 1你会得到同一天。

另请注意,如果您不想要星期一,您还可以在方法中指定日期编号:

thursday_next_week = Date.commercial(now.cwyear,now.cweek+1,4) #=> 2012-03-15

答案 1 :(得分:3)

使用Date个对象计算日期非常简单。如果您只想从给定的Date对象获取上一周/下周,请使用以下内容:

date = Date.today
previous_week = (date - 7).cweek
next_week = (date + 7).cweek

答案 2 :(得分:1)

在ActiveSupport中,您有帮助将Fixnum转换为时间http://as.rubyonrails.org/classes/ActiveSupport/CoreExtensions/Numeric/Time.html使用:

date = Date.today
week_ago = date - 1.week
next_week = date + 1.week

答案 3 :(得分:1)

假设您的意思是“当前年份中的给定周数”,您可以执行以下操作:

2.weeks.since(Time.gm(Time.now.year))
=> Fri Jan 15 00:00:00 UTC 2010

替换上面的1中的(week_number - 1),你将得到所需周的日期。

答案 4 :(得分:0)

我创建了一些方法来获取给定日期的周数 像这样的东西:

def self.get_week(date)
    year = date.year
    first_monday_of_the_year = self.get_first_monday_of_the_year(year)
    # The first days of January may belong to the previous year!
    if date < first_monday_of_the_year
      year -= 1
      first_monday_of_the_year = self.get_first_monday_of_the_year(year)
    end
    day_difference = date - first_monday_of_the_year
    week = (day_difference / 7).to_i + 1
    week
  end

   def self.get_monday_of_year_week(year, week)
    d = self.get_first_monday_of_the_year(year)
    d + ((week - 1) * 7).days
  end

  def self.get_first_monday_of_the_year(year)
    d = Date.new(year, 1, 7)  # 7 Jan is always in the first week
    self.get_monday_of_week(d)
  end

  def self.get_monday_of_week(date)
    wday = (date.wday + 6) % 7
    date - wday.days
  end