ruby-on-railsrubydatetime

How to convert a Date to the midday Time in UTC in Ruby-on-Rails, regardless of the timezone?


I have a Date instance in Ruby-on-Rails. I would like to convert it into the midday in Time in UTC. How can I do it?

I thought this would work.

date = Date.new(2024, 10, 20)
time = date.to_time + Time.now.gmt_offset + 3600*12
  # => 2024-10-20 12:00:00 +0100
time.utc
  # => 2024-10-20 11:00:00 UTC

I think it did work, but it seems it doesn't work anymore; it gives 11 o'clock in UTC as opposed to 12... Considering the 1-hour difference, I suspect it is related to the fact my machine is in the UK timezone. But how come?

A lot of past articles and Q&As referred to DateTime in Ruby. However, DateTime has been deprecated in Ruby (see, for example, this article in 2020). So, I would like to get a Time.

What is the (best) way to achieve this in Ruby 3 and Rails 7?


Solution

  • In plain Ruby, you can pass the date values to Time.utc and set the hour explicitly, no need to calculate any timezone offsets:

    date = Date.new(2024, 10, 20)
    
    Time.utc(date.year, date.month, date.day, 12)
    #=> 2024-10-20 12:00:00 UTC