Object
Deserializes JSON
string by converting time since epoch to Time
# File json/lib/json/add/time.rb, line 9 def self.json_create(object) if usec = object.delete('u') # used to be tv_usec -> tv_nsec object['n'] = usec * 1000 end if method_defined?(:tv_nsec) at(object['s'], Rational(object['n'], 1000)) else at(object['s'], object['n'] / 1000) end end
Returns a hash, that will be turned into a JSON
object and represent this object.
# File json/lib/json/add/time.rb, line 22 def as_json(*) nanoseconds = [ tv_usec * 1000 ] respond_to?(:tv_nsec) and nanoseconds << tv_nsec nanoseconds = nanoseconds.max { JSON.create_id => self.class.name, 's' => tv_sec, 'n' => nanoseconds, } end
There are two Time classes. There's one that is part of core Ruby and there is an additional Time class that is part of the standard library.
The standard library Time class extends the core Time class by adding some methods. If you are using the standard library Time class and cannot find documentation for a method, look at the API docs for the core Time class.
Q: Given some number of seconds, how can that be converted into minutes and remainder seconds?
A: There are a few ways. Assume we start with 1234 seconds.
Time.at(1234).strftime "%M:%S" # This returns a String
If you want numerical values, you can do some basic math:
m, s = 1234/60, 1234%60
That second example may be a little too terse for general use. You can wrap it in a method:
def minutes_and_remainder_seconds seconds
[seconds/60, seconds%60]
end
minutes, seconds = *minutes_and_remainder_seconds(1234)
You may want to make this available to multiple classes. You can put it in a module ...
module TimeUtilities
def minutes_and_remainder_seconds seconds
[seconds/60, seconds%60]
end
end
... and then include that module in those classes that use it:
class Foo
include TimeUtilities
# additional class stuff ....
end
Thanks to Andrey Andreevich Ostapchuck and J Bolton for their suggestions on this.