Reputation: 8451
I'm trying to update a DateTime object with time of day. Here is what I'm currently trying to do:
time_of_day = schedule.start_at.strftime("%H:%M:%S")
specific_day_of_next_month(schedule.start_at) + time_of_day
the variable specific_day_of_next_month returns this value:
=> Thu, 27 Aug 2020 00:00:00 +0000
and time_of_day has this output.
=> "14:45:53"
So I'm basically trying to put them together. But when I run that I get this error:
TypeError: expected numeric
Any idea how I can do this?
Upvotes: 1
Views: 889
Reputation: 110685
require 'time'
dt = DateTime.new(2017, 8, 4)
time_to_add = "14:45:53"
hour, min, sec = time_to_add.split(":").map(&:to_i)
DateTime.new(dt.year, dt.month, dt.day, hour, min, sec)
#=> #<DateTime: 2017-08-04T14:45:53+00:00 ((2457970j,53153s,0n),+0s,2299161j)>
or
(dt.to_time + [3600, 60, 1].zip(time_to_add.split(':')).
reduce(0) { |tot,(sec,t)| tot + t.to_i*sec }).to_datetime
#=> #<DateTime: 2017-08-04T14:45:53+00:00 ((2457970j,53153s,0n),+0s,2299161j)>
Upvotes: 1
Reputation: 2747
You can use DateTime#change
. Something like this:
time_arr = time_of_day.split(':')
h = {hour: time_arr[0].to_i, min: time_arr[1].to_i, sec:time_arr[2].to_i}
specific_day_of_next_month(schedule.start_at).change(h)
NOTE: I'm assuming time_of_day
as string, like "14:45:53".
Upvotes: 1