Search code examples
ruby-on-railsrubytimezonedst

How do I convert a `DateTime` to the corresponding date and time in Berlin?


Given a (UTC) DateTime object, how can I get the corresponding time in Berlin, in CET or CEST, depending on the date?

Examples for the desired "convert" function:

convert(DateTime.new(2018, 07))
=> Sun, 01 Jul 2018 02:00:00 +0200
convert(DateTime.new(2018, 12))
=> Sat, 01 Dec 2018 01:00:00 +0100

Solution

  • Try this

    require 'tzinfo'
    
    timezone = TZInfo::Timezone.get('Europe/Berlin')
    local_time = timezone.utc_to_local(utc_time)
    

    That even works without Rails.