Pregunta

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?

¿Fue útil?

Solución

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

Otros consejos

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)

BubbleWrap adds some nice wrappers around this:

Time

The Time Ruby class was added a class level method to convert a iso8601 formatted string into a Time instance.

Time.iso8601("2012-05-31T19:41:33Z")
=> 2012-05-31 21:41:33 +0200

This will give you a NSDate instance, simple as that.

Maybe this has since been fixed. I'm parsing times in RubyMotion no problem.

(main)> Time.parse("2016-01-21 10:33:07")
=> "2016-01-21 10:33:07 -0800"

RubyMotion 4.8

$ motion --version
4.8
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top