我尝试将时间的文本表示解析为ruby Time对象.
通常在ruby中,我会这样做:
require 'time'
Time.parse('2010-12-15T13:16:45Z')
# => 2010-12-15 13:16:45 UTC
Run Code Online (Sandbox Code Playgroud)
在RubyMotion中,我无法使用libs,并且Time.parse不可用:
(main)> require 'time'
=> #<RuntimeError: #require is not supported in RubyMotion>
(main)>
(main)> Time.parse
=> #<NoMethodError: undefined method `parse' for Time:Class>
Run Code Online (Sandbox Code Playgroud)
有没有办法要求ruby提供的时间库,而不必复制和重写整个代码,使其与RubyMotion兼容?
Pau*_*l.s 11
它不是自动的,但你可以使用 NSDateFormatter
date_formatter = NSDateFormatter.alloc.init
date_formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
date = date_formatter.dateFromString "2010-12-15T13:16:45Z"
puts date.description
Run Code Online (Sandbox Code Playgroud)
wnd*_*ori 11
虽然Paul.s的答案肯定有效,但是它给了我毛骨悚然,在我的代码中查看它,所以我一直在寻找.
Matt Aimonetti的MacRuby书中有一些好东西:
解析的地方很简单:
NSDate.dateWithString(<your date string here>)
Run Code Online (Sandbox Code Playgroud)
要么
NSDate.dateWithNaturalLanguageString(<all kinds of date strings>)
Run Code Online (Sandbox Code Playgroud)
如果你必须有一个Time对象:
Time.at(NSDate.date)
Run Code Online (Sandbox Code Playgroud)