Get date range from one date

I can do it myself, of course, but there is built-in functionality in Ruby or in a library that would allow me to do something like this

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

thank

+3
source share
2 answers

Use ActiveSupport . However, he sees 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

More work is needed if it 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)

leads to

Mon, 25 Jan 2010
[Sun, 24 Jan 2010, Sat, 30 Jan 2010]
Sun, 24 Jan 2010
[Sun, 24 Jan 2010, Sat, 30 Jan 2010]
+6
source

Days are 0..6, Sunday is 0.

date = Time.now
puts date.wday 

displays the current digital code of the week.

What are you trying to accomplish?

by adding or subtracting the number of seconds per day that you receive on another date exactly 1 day later.

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

Source: https://habr.com/ru/post/1729929/


All Articles