How do I get Ruby to parse time as if it were in a different time zone?

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?


在解析它之前,您可以将UTC时区名称追加到字符串中:

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

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.


一个没有Time.zone的@Pete Brumm的回答set / unset

Time.zone.parse("Tue Nov 23 23:29:57 2010") + Time.zone.utc_offset
链接地址: http://www.djcxy.com/p/40902.html

上一篇: 来自Olson时区的.NET TimeZoneInfo

下一篇: 我如何让Ruby解析时间,就好像它在不同的时区一样?