'changing or adding hours to a datetime in ruby

im having a problem with datetime in rails. Im reading a json and saving dates in a model. that has a column t.date:datetime The thing is there is 2 dates that i get from this json, and i want only to save it as 1.
I get date for day : 2022-04-16 00:00:00 and also i get a hour date : 01:00:00 is there a way to add that hour date to my day date ? Like getting 2022-04-16 01:00:00 ?

Im new to rails so sorry if im not explaining correctly.



Solution 1:[1]

You can convert your time to second and then add it to your date

date = "2022-04-16 00:00:00".to_datetime
time = Time.parse("01:00:00").seconds_since_midnight.seconds

date + time

You don't need to do to_datetimeif your date is already a datetime object

Solution 2:[2]

An hour is 1/24th of a day. DateTime happily let's you add that to a date.

t1 = DateTime.today
t2 = t1 + 1/24r # a rational number. 1.0/24 is fine too.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gaeguri
Solution 2 steenslag