Parsing a string in RubyMotion

I am trying to parse a textual representation of 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 cannot 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 ruby-provided time library without having to copy and rewrite all the code to make it compatible with RubyMotion?

+4
source share
4 answers

It is not so automatic, but you can 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 
+11
source

While Paul.s answers, of course, it works, it gave me creeps while looking at it in my code, so I continued to look.

Matt Aimonanetti Macruby's book has good things:

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 the parsing is simple as:

 NSDate.dateWithString(<your date string here>) 

or

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

And if you absolutely need to have a Time object from this:

 Time.at(NSDate.date) 
+11
source

BubbleWrap adds some interesting wrappers around this:

Time

A class level method has been added to the Time Ruby class to convert the iso8601 formatted string to a Time instance.

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

This will give you an instance of NSDate simple in that.

+2
source

Perhaps this has been fixed. I parsing time in RubyMotion is not a problem.

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

RubyMotion 4.8

 $ motion --version 4.8 
0
source

Source: https://habr.com/ru/post/1413912/


All Articles