查找给定周数的日期 [英] Finding the date for a given week number

查看:121
本文介绍了查找给定周数的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  date = Date.today#2012年3月5日,星期一
puts date.cwyear#2012
put date.cweek#10(2012年第10周)

现在我知道本周是,我想知道下周和上周是什么。我需要年(2012)和周数(10),并将其重新转换成日期对象,以便我可以计算下一个/上一周的值。我该怎么做?

解决方案

你想要 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#=>请注意,星期一星期几开始,所以如果你是星期天的,请问下一个星期一 - 你会得到同一天。



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

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


I am trying to do some date math based on the week number of a given year. For example:

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

Now that I know what the current week is, I want to figure out what the next week and previous week are. I need to take the year (2012) and the week number (10) and turn it back into a date object so I can calculate the value for the next/previous week. How can I do this?

解决方案

You want 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

Note that weeks start on Monday, so if you are on a Sunday and ask for next monday - 1 you'll get the same day.

Note also that if you don't want Mondays you can also specify the day number in the method:

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

这篇关于查找给定周数的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆