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
Best Practices For Reusing Code Between Controllers in Ruby on Rails
Getting Fields_For and Accepts_Nested_Attributes_For to Work With a Belongs_To Relationship
Where Is the Rails Method That Converts Data from 'Datetime_Select' into a Datetime Object
How to Read Lines of a File in Ruby
Devise Custom Routes and Login Pages
Why Isn't Current Directory on My Ruby Path
Google Plus API Shutdown Today, Which Alternative Can Be Used to Authentication
Rails Assets:Precompile Yarn Executable Was Not Detected in the System
The Class/Object Paradox Confusion
Serving Static Files With Sinatra
Rails 3 Disabling Session Cookies
Ruby Method Lookup Path For an Object
How to Install Therubyracer Gem on 10.10 Yosemite
Uniq by Object Attribute in Ruby
Can't Install Pg Gem on Windows
Why Should We Avoid Using Class Variables @@ in Rails
Ruby on Rails Callback, What Is Difference Between :Before_Save and :Before_Create