How to Convert Datetime.Now to Utc in Ruby

How do I Convert DateTime.now to UTC in Ruby?

d = DateTime.now.utc

Oops!

That seems to work in Rails, but not vanilla Ruby (and of course that is what the question is asking)

d = Time.now.utc

Does work however.

Is there any reason you need to use DateTime and not Time? Time should include everything you need:

irb(main):016:0> Time.now
=> Thu Apr 16 12:40:44 +0100 2009

Convert DateTime String to UTC in rails

Time.parse("2010-01-01 12:30:00").getutc

EDIT

(grinding teeth while thinking about the nightmare which is Ruby/Rails date/time handling)

OK, how about this:

Time.zone.parse("2010-01-01 12:30:00").utc

Note that Time.zone.parse returns a DateTime, while appending the .utc gives you a Time. There are differences, so beware.

Also, Time.zone is part of Rails (ActiveSupport), not Ruby. Just so you know.

Converting datetime with one timezone to utc

Using the strptime method on the Rails DateTime class, you can parse a DateTime object from a string containing both the time and timezone (timezone is passed via the %z directive). From there, you can convert the time to UTC:

a = "04/23/2014 04:00"
b = "Eastern Time (US & Canada)"

datetime_with_tz = DateTime.strptime([a, b].join(' '), "%m/%d/%Y %H:%M %z")
#=> Wed, 23 Apr 2014 04:00:00 -0500

datetime_with_tz.utc
#=> Wed, 23 Apr 2014 09:00:00 +0000

How to convert UTC to EST/EDT in Ruby?

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 Topics



Leave a reply



Submit