简体   繁体   English

将String转换为DateTime Ruby

[英]Convert String to DateTime Ruby

I have a string "2015-11-01T10:00:00.00+08:00" extracted from json response. 我从json回复中提取了一个字符串"2015-11-01T10:00:00.00+08:00" 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. 我尝试了Time.new("2015-11-01T10:00:00.00+08:00")它返回2015-01-01 00:00:00 +0530 ,显然日期在这里和时间都有所改变。

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 : 使用Rails,根据您的需要,建议使用:

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

vs 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.zone.parse将返回您的时区中表示的日期时间。

Time#parse : 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. 在rails console中工作。

If it's just plain ruby, go for @mudasobwa's solution 如果它只是普通的红宝石,请选择@ mudasobwa的解决方案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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