2015-11-09 73 views
0

我需要来自数据库日期,如"2015-08-27T12:09:36Z"。我试过,但没有得到任何解决方案,我得到date and time in different variable.如何从DB日期获取Ruby日期时间

我需要得到它在RubyNo rails在我的应用程序中。

我用下面的代码,但没有得到。

Time.strptime("2015-08-27T12:09:36Z", "%Y-%m-%dT%H:%M:%S%z").in_time_zone 

任何人都有经验吗?

感谢

+1

看一看['Date.parse()'](http://ruby-doc.org/stdlib-2.2.2/libdoc/date/rdoc/Date.html#method-c-解析)及其朋友'Time.parse()'。 – sschmeck

回答

0

我没有足够的信誉评论使我张贴作为答案评论,你找这个

Time.now.strftime('%Y-%m-%dT%H:%M:%SZ') 

,这将给你要求的模式。 Z表示如果使用

%z - Time zone as hour and minute offset from UTC (e.g. +0900) 
      %:z - hour and minute offset from UTC with a colon (e.g. +09:00) 
      %::z - hour, minute and second offset from UTC (e.g. +09:00:00) 
    %Z - Time zone abbreviation name 

检查更

http://apidock.com/ruby/Time/strftime

我更新的答案时区您的评论

require 'date' 

DateTime.parse("2015-08-27T12:09:36Z").strftime('%Y-%m-%dT%H:%M:%SZ') 

在您的代码更改后Time.strptime('')DateTime.strptime('')

+0

不符合Time.now ..我需要做...数据库日期.. – user1780370

0

首先,您需要require 'date'。 Ruby内置了DateTime类,没有require,但该库提供了更多功能。

如果您有从ISO-8601格式的数据库中检索到的字符串,并且想将其转换为日期和时间,只需使用DateTime.iso8601(string)即可获取DateTime对象。您可以随后提取日期和时间组件,不过您可以随时取而代之。

irb(main):001:0> require 'date' #=> true 
irb(main):002:0> dt = DateTime.iso8601("2015-08-27T12:09:36Z") # DateTime object 
irb(main):003:0> d = dt.to_date # Date object 
irb(main):004:0> t = dt.to_time # Time object