55

I'm parsing something like this:

11/23/10 23:29:57

which has no time zone associated with it, but I know it's in the UTC time zone (while I'm not). How can I get Ruby to parse this as if it were in the UTC timezone?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
farhadf
  • 1,918
  • 3
  • 19
  • 27

7 Answers7

46

You could just append the UTC timezone name to the string before parsing it:

require 'time'
s = "11/23/10 23:29:57"
Time.parse(s) # => Tue Nov 23 23:29:57 -0800 2010
s += " UTC"
Time.parse(s) # => Tue Nov 23 23:29:57 UTC 2010
maerics
  • 151,642
  • 46
  • 269
  • 291
34

credit from https://rubyinrails.com/2018/05/30/rails-parse-date-time-string-in-utc-zone/,

Time.find_zone("UTC").parse(datetime)
# => Wed, 30 May 2018 18:00:00 UTC +05:30
new2cpp
  • 3,311
  • 5
  • 28
  • 39
25

If your using rails you can use the ActiveSupport::TimeZone helpers

current_timezone = Time.zone
Time.zone = "UTC"
Time.zone.parse("Tue Nov 23 23:29:57 2010") # => Tue, 23 Nov 2010 23:29:57 UTC +00:00
Time.zone = current_timezone

It is designed to have the timezone set at the beginning of the request based on user timezone.

Everything does need to have Time.zone on it, so Time.parse would still parse as the servers timezone.

http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html

Note: the time format you have above was no longer working, so I changed to a format that is supported.

Mike Lyons
  • 1,748
  • 2
  • 20
  • 33
Pete Brumm
  • 1,656
  • 19
  • 13
10

If you are using ActiveSupport [from Rails, e.g], you can do this:

ActiveSupport::TimeZone["GMT"].parse("..... date string")
Bret Weinraub
  • 1,943
  • 15
  • 21
9

Another pure Ruby (no Rails) solution if you don't want/need to load ActiveSupport.

require "time"

ENV['TZ'] = 'UTC'
Time.parse("2019/10/01 23:29:57")
#=> 2019-10-01 23:29:57 +0000
Cimm
  • 4,653
  • 8
  • 40
  • 66
5

Without rails dependencies: Time parses in local time but DateTime parses in UTC. Then you can transform it to a Time class if that's what you want:

require 'date'

DateTime.parse(string_to_parse).to_time
jBilbo
  • 1,683
  • 13
  • 24
4

An aliter to @Pete Brumm's answer without Time.zone set/unset

Time.zone.parse("Tue Nov 23 23:29:57 2010") + Time.zone.utc_offset
Vignesh Jayavel
  • 984
  • 11
  • 11