Home > Blockchain >  How to convert UTC to EST/EDT in Ruby?
How to convert UTC to EST/EDT in Ruby?

Time:03-27

How do I convert UTC timestamp in the format '2009-02-02 00:00:00' to EST/EDT in Ruby? Note that I am not using Rails, instead it is a simple Ruby script.

1If the date range falls between EST (usually Jan-Mid March) it needs to to UTC-5hrs. For EDT it is UTC-4hrs.

So far I have the following function to convert UTC to EST/EDT.

def utc_to_eastern(utc)
    eastern = Time.parse(utc) # 2009-02-02 00:00:00 -0500
    offset_num = eastern.to_s.split(" -")[1][1].to_i # 5
    eastern_without_offset = (eastern-offset_num*60*60).strftime("%F %T") # 2009-02-01 19:00:00
    return eastern_without_offset
end

puts utc_to_eastern("2009-02-02 00:00:00") # 2009-02-01 19:00:00
puts utc_to_eastern("2009-04-02 00:00:00") # 2009-04-01 20:00:00

The above code does what I want, however there's two issues with my solution:

  1. I do not want to reinvent the wheel, meaning I do not wish to write the time conversion functionality instead use existing methods provided by Ruby. Is there a more intuitive way to do this?
  2. The parsing uses my local timezone to convert UTC to EST/EDT, however I would like to explicitly define the timezone conversion ("America/New_York"). Because this means someone running this on a machine on central time would not be using EST/EDT.

CodePudding user response:

The best approach would be to use TZInfo.

require 'tzinfo'
require 'time'

def utc_to_eastern utc
  tz = TZInfo::Timezone.get("America/New_York")
  tz.to_local(Time.parse(utc)).strftime('%Y-%m-%d %H:%M:%S')
end

utc_to_eastern "2020-02-02 00:00:00 UTC" => "2020-02-01 19:00:00"
utc_to_eastern "2020-04-02 00:00:00 UTC" => "2020-04-01 20:00:00"
  • Related