Parsing string to time in RubyMotion

放肆的年华 提交于 2019-12-22 09:37:09

问题


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?


回答1:


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



回答2:


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)



回答3:


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.




回答4:


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


来源:https://stackoverflow.com/questions/10718099/parsing-string-to-time-in-rubymotion

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!