Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a comprehensive library/module for ISO 8601 in ruby?

Is there already an implementation of all the date, time, duration and interval usage of the ISO 8601 standard in ruby? I mean something like a Class where you can set and get the details like, year, month, day, day_of_the_week, week, hour, minutes, is_duration?, has_recurrence? and so on which also can be set by and exported to a string?

like image 399
dStulle Avatar asked Nov 15 '10 21:11

dStulle


2 Answers

require 'time'

time = Time.iso8601 Time.now.iso8601 # iso8601 <--> string
time.year    # => Year of the date 
time.month   # => Month of the date (1 to 12)
time.day     # => Day of the date (1 to 31 )
time.wday    # => 0: Day of week: 0 is Sunday
time.yday    # => 365: Day of year
time.hour    # => 23: 24-hour clock
time.min     # => 59
time.sec     # => 59
time.usec    # => 999999: microseconds
time.zone    # => "UTC": timezone name

Have a look at the Time. It has a lot of stuff in it.

Unfortunately Ruby's built-in Date-Time functions do not seem to be well thought through (comparing to .NET for example), so for other functionality you will need to use some gems.

Good thing is that using those gems does feel like it's a built-into Ruby implementation.

Most useful probably is Time Calculations from ActiveSupport (Rails 3).
You don't need to require the rails but only this small library: gem install activesupport.

Then you can do:

require 'active_support/all'
Time.now.advance(:hours => 1) - Time.now # ~ 3600
1.hour.from_now - Time.now # ~ 3600 - same as above
Time.now.at_beginning_of_day # ~ 2010-11-24 00:00:00 +1100
# also at_beginning_of_xxx: xx in [day, month, quarter, year, week]
# same applies to at_end_of_xxx

There are really a lot of things that you can do and I believe you will find what suites your needs very well.

So instead of giving you abstract examples here I encourage you to experiment with irb requiring active_support from it.

Keep the Time Calculations at hand.

like image 64
Dmytrii Nagirniak Avatar answered Nov 03 '22 18:11

Dmytrii Nagirniak


Ruby Time library adds an iso8601 method to the Time class. See here.

I don't know of a gem that exports the other ISO 8601 formats. You could extend the Time class yourself to add them.

Often you'll use the strftime method to print out specific formats. Example.

like image 33
Larry K Avatar answered Nov 03 '22 17:11

Larry K