Data and Time in Ruby
Ruby is similar to other language in its support for date and time but adds its own methods that makes it easier to work with date and time objects.
Ruby employs native to C programming language time and date library. Time class in Ruby has quite a few methods listed below
t = Time.at(0)
t.sec, t.hour, t.day, t.month, t.year, t.wday, t.yday, t.isdst, t.zone
The latest version of Ruby uses a signed 63-bit integer which represents the largest possible number in 64 bit OS.
In order to get time zero you called on DateTime.new.to_s method of the DateTime class. You can also obtain today’s date by making a call to DateTime::now.to_s method of the DateTime class.
There are two classes that resent time in Ruby: Time and DateTime. It is important to know the difference between two classes as represented in the following table
Time
|
Time Class |
DateTime Class |
Date Range |
1901-2037 |
Infinite |
Daylight Saving Time |
Yes |
No |
Calendar Reform |
No |
Yes |
Time zone |
Requires tz gem |
Requires time zone offsets |
Time format like RFC822 |
Built in |
Need to write yourself |
Speed |
Fast |
Slow |
The Time and DateTime classes support iterators and data arithmetic. However, it is important to remember that Time is stored in second while DateTime is stored as number of days. Both classes support bi-directional conversion of types between Time and DateTime.
In addition, we would like to touch upon Date parsing which is also available in Ruby. In order to parse a date, you would eploy parse method of the Date class
Require ‘date’
Date.parese(‘1/1/2015’).to_s
Finally, you may need to use commercial date versus standard date. The main difference between the two is in treatment of Sunday which is part of the weekend for commercial date and not first date of the week for standard.