Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 583
mordaroso Avatar asked Nov 29 '22 09:11

mordaroso


2 Answers

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
like image 159
Paul.s Avatar answered Nov 30 '22 23:11

Paul.s


While Paul.s answer certainly works, it was giving me the creeps, looking at it in my code, so I kept looking.

Matt Aimonetti's MacRuby book has some good stuff:

http://books.google.ca/books?id=WPhdPzyU1R4C&pg=PA43&lpg=PA43&dq=macruby+nsdate&source=bl&ots=j7Y3J-oBcV&sig=FTr0KyKae-FinH-HNEWBcAAma1s&hl=en&sa=X&ei=ANT0T7mkEM6jqwHx7LjeAw&ved=0CGEQ6AEwBA#v=onepage&q=macruby%20nsdate&f=false

Where parsing is as simple as:

NSDate.dateWithString(<your date string here>)

or

NSDate.dateWithNaturalLanguageString(<all kinds of date strings>)

And if you absolutely have to have a Time object from that:

Time.at(NSDate.date)
like image 25
wndxlori Avatar answered Nov 30 '22 21:11

wndxlori