开发者

Ruby DateTime.Parse to local time

开发者 https://www.devze.com 2023-03-04 04:14 出处:网络
I have a date string 20101129220021, so I will use require \'date\' d = DateTime.parse(\'20101129220021\')

I have a date string 20101129220021, so I will use

require 'date'
d = DateTime.parse('20101129220021')

This part works fine, and I get a date, which is in UTC.

My question 开发者_如何学Gois, how can I convert this into my local time? I tried many methods like extracting the time part using d.to_time and manipulate the result, but it didn't work. As far as I know, DateTime object is immutable. Can I please get some help?


irb(main):001:0> require "date"
=> true
irb(main):002:0> d = DateTime.parse('20101129220021')
=> #<DateTime: 2010-11-29T22:00:21+00:00 (70719276007/28800,0/1,2299161)>
irb(main):003:0> d.to_time
=> 2010-11-30 00:00:21 +0200

ruby 1.9.2p180 (2011-02-18)


You can add a rational fraction based on the timezone to get the local time.

require 'date'

# Make this whatever your zone is. Using UTC +0300 here.
ZONE = 3

d = DateTime.parse('20101129220021') + Rational(ZONE,24)

d.to_s # => "2010-11-30T01:00:21+00:00"
0

精彩评论

暂无评论...
验证码 换一张
取 消