开发者

Obtain a date range from a single date

开发者 https://www.devze.com 2022-12-18 12:49 出处:网络
I can do this myself of course, but is there built-in f开发者_JS百科unctionality in Ruby, or a library, that would let me do something like this

I can do this myself of course, but is there built-in f开发者_JS百科unctionality in Ruby, or a library, that would let me do something like this

date = Time.now
sunday = date.week.first_day
saturday = date.week.last_day

Thanks


Use the ActiveSupport gem. It, however, considers Monday as the start of the week.

require 'active_support'
d = Date.today                     # => Mon, 25 Jan 2010
sun = d.beginning_of_week - 1.day  # => Sun, 24 Jan 2010
sat = d.end_of_week - 1.day        # => Sat, 30 Jan 2010

Needs more work if today is Sunday

def week_ends(date)
  sun = date.beginning_of_week - 1.day
  sat = date.end_of_week - 1.day
  if date.sunday?
    sun += 1.week
    sat += 1.week
  end
  [sun, sat]
end

p d = Date.today
p week_ends(d)

p d = Date.yesterday
p week_ends(d)

results in

Mon, 25 Jan 2010
[Sun, 24 Jan 2010, Sat, 30 Jan 2010]
Sun, 24 Jan 2010
[Sun, 24 Jan 2010, Sat, 30 Jan 2010]


Days are represented by 0..6, Sunday being 0.

date = Time.now
puts date.wday 

would output todays number code of the week.

What are you trying to accomplish?

by adding or subtracting the number of seconds in a day you get to a different date exactly 1 day from now.

date = Time.now
puts date + 86400 #will be tomorrow
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号