Search code examples
rubyrubymotion

Parsing string to time in RubyMotion


I try to parse a text representation of a time into a ruby Time object.

Normally in ruby I would do it like this:

require 'time'
Time.parse('2010-12-15T13:16:45Z')
# => 2010-12-15 13:16:45 UTC

In RubyMotion I am unable to require libs and Time.parse is not available:

(main)> require 'time'
=> #<RuntimeError: #require is not supported in RubyMotion>
(main)>
(main)> Time.parse
=> #<NoMethodError: undefined method `parse' for Time:Class>

Is there a way to require the time library provided by ruby without having to copy and rewrite the whole code to make it compatible with RubyMotion?


Solution

  • It's not as automatic, but you could use 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