migu
migu

Reputation: 4336

Ruby: Apply time and day of week to a DateTime

Question:

What's the easiest way to take a DateTime object "A" and apply the day of week and time of another DateTime object "B" so that I have a new DateTime object that's in the week of DateTime object "A" but has the day of week and time of DateTime object "B"?

Some context:

I'm creating a scheduling app where users have recurring appointments. All users set their default day of week and time in form of a DateTime object (I save it as a DateTime but actually I don't care about the date itself).

When I want to extend their recurring appointments (e.g. for another 6 months), I need to get the week of their last appointment, jump to the default day of week and time within that week and extend from there.

Upvotes: 2

Views: 58

Answers (1)

Cary Swoveland
Cary Swoveland

Reputation: 110685

require 'date'

def new_date_time(a,b)
  a_date = a.to_date
  new_date = a_date + (b.to_date.wday - a_date.wday)
  DateTime.new(new_date.year, new_date.month, new_date.day,
    b.hour, b.minute, b.second)
end

a = DateTime.new(2015,8,6,4,5,6) # Thursday
  #=> #<DateTime: 2015-08-06T04:05:06+00:00 ((2457241j,14706s,0n),+0s,2299161j)> 
b = DateTime.new(2015,8,3,13,21,16) # Monday
new_date_time(a,b)
  #=> #<DateTime: 2015-08-03T13:21:16+00:00 ((2457238j,48076s,0n),+0s,2299161j)> 

b = DateTime.new(2015,11,17,13,21,16) # Tuesday
new_date_time(a,b)
  #=> #<DateTime: 2015-08-04T13:21:16+00:00 ((2457239j,48076s,0n),+0s,2299161j)> 

Upvotes: 2

Related Questions