简体   繁体   中英

Convert String to DateTime Ruby

I have a string "2015-11-01T10:00:00.00+08:00" extracted from json response. How can convert it to Time or DateTime?

I tried Time.new("2015-11-01T10:00:00.00+08:00") its returning 2015-01-01 00:00:00 +0530 , clearly the date is changed here and time too.

require 'date'

▶ Date.parse "2015-11-01T10:00:00.00+08:00"
#⇒ #<Date: 2015-11-01 ((2457328j,0s,0n),+0s,2299161j)>

▶ DateTime.parse "2015-11-01T10:00:00.00+08:00"
#⇒ #<DateTime: 2015-11-01T10:00:00+08:00 ((2457328j,7200s,0n),+28800s,2299161j)>

or, even better:

▶ DateTime.iso8601 "2015-11-01T10:00:00.00+08:00"
#⇒ #<DateTime: 2015-11-01T10:00:00+08:00 ((2457328j,7200s,0n),+28800s,2299161j)>

With Rails, depending on your needs, it's recommended to use :

Time.zone.parse("2015-11-01T10:00:00.00+08:00")
#=> Sun, 01 Nov 2015 02:00:00 UTC +00:00 

vs

Time.parse("2015-11-01T10:00:00.00+08:00")
#=> 2015-11-01 10:00:00 +0800

Time.zone.parse will return a Datetime expressed in your Timezone.

Time#parse :

require 'time'
Time.parse("2015-11-01T10:00:00.00+08:00")

If it's in rails, just do

"2015-11-01T10:00:00.00+08:00".to_time

worked in rails console.

If it's just plain ruby, go for @mudasobwa's solution

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM