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. 

Featured pages

Ruby

Set of Ruby Object Oriented Programming Language tutorials that cover such topics as Ruby strings, …

Rails

Rails Framework tutorial teaches you how to utilize de facto framework of choice for Ruby developme…

Ruby Duck Typing

“If an object quacks like a duck just go ahead and treat it as a duck” – this fun…

Regular Expressions

Ruby uses the =~ operator to check any given string against regular expression. For example, a stri…

Credit Card Number

Every last digit of any credit card is a check sum digit that is determined by all digits in front …

Ruby Arrays

Ruby Programming Language has built in support for Arrays. Arrays help you define some of the compl…

Ruby Hashes

Hashes are very similar to arrays in Ruby and hashes interface is similar to Ruby array interface. …

Ruby Code Block

Ruby is very unique language when it comes to code blocks. You can simply pass a code block to a me…