Date and Time in Ruby

First post of the new year, so I think it would be good to revisit one of the most commonly used classes in Ruby, the Date and Time classes.

DATE

The Date class in Ruby does not have any concept of any variables relating to time (Hour, Minutes, Seconds). Simply put, it will only show the Year, Month, and Day values of any given date. To use the date class we simply use require ‘date’.

Most common usage would be Date.today. Keep in mind that calling Date.new will yield a negative date and is not an alias for ‘today’. To add/subtract for the date, simply performing a Date.today + 1 will add 1 day to the current date

DATE CONSTANTS

If you need to access the months and days of the week, the Date class have you covered with its constants.

> Date::MONTHNAMES

=> [nil, “January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”]

Note that the index 0 is a nil value.

> DATE::DAYNAMES

=> [“Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”]

You can use the .rotate(1) if you wanted Monday to be the first day of the week instead.

TIME

To manage anything related to time, the Time class should be used. This class is consists of the Date values plus the Hour, Minutes, and Seconds. The value however is represented as a number of seconds since Epoch, known as Unix time.

There are several ways a Time can be initialized. The most common is via Time.now or Time.new which will both result in the current date/time.

You may also create a new Time by initializing it with a Unix timestamp via the .at(?) method.

> Time.at(1451600000)
=> 2016-01-01 06:13:20 +0800

You may access each part/component of the Time object by using the following methods:

  • :year => 2016
  • :month => 1
  • :day => 1
  • :hour => 6
  • :min => 13
  • :sec => 20

There also predicate methods available to for instance check if the current date/time is a :monday?, :tuesday?, :wednesday?, and so on which results in a true or false.

TIMEZONES

A Time class also responds the method :zone and is shown in the above example with the value of +0800. The result is a timezone abbreviation as shown below

> t = Time.now
> t.zone
=> “PHT”

You can also convert the said local time, to its equivalent UTC (GMT) time via the t.gmtime or t.utc.

Addition and subtraction with Time is the same as the Date class. The only difference is that calling Time.now + 10 will add seconds and not days.

 ACTIVESUPPORT

Rails provide extended convenience methods for numeric, date, datetime, and time data types. Useful examples of these are the n.days.ago, Date.tomorrow, Time.beginning_of_day, Time.beginning_of_week, and much more.

Conversion from timezones other than UTC are also supported via the :in_time_zone method which accepts a Rails timezone as its parameter. The list of supported timezones can be accessed in the ActiveSupport::TimeZone::MAPPING constant.

> t = Time.now
=> 2016-01-01 06:13:20 +0800

> t.in_time_zone(‘Pacific Time (US & Canada)’)
=> Thu, 31 Dec 2015 14:13:20 PST -08:00

Addition and subtraction can also be done using the convenience methods like so

> Date.current + 5.days.ago
> t = Time.now
> t.end_of_week + 3.days

DATETIME

Both the Time and DateTime have access to the same methods. The main difference is simply that the Time is done using C while the DateTime is in Ruby. The Time class will be a bit faster

PARSING AND FORMATTING

In order to present dates and time info, some parsing and formatting needs to be done. The most common methods used are the :parse and :strptime for dates and :strftime for time data types. A list of available formatting can be found here. Below are the common examples of date time formatting and parsing.

> Date.parse(“9/9/2015”)  # -> 2015-09-09
> Date.parse(“January 2”) # -> 2016-01-02
> Date.parse(“May I have a cup of coffee, please?”) # -> 1 of May
> Date.strptime(“2 of October”, “%d of %B”) # 2015-10-02

> time = Time.new

> time.strftime(“%d/%m/%Y”)        # “05/12/2015”
> time.strftime(“%k:%M”)           # “17:48”
> time.strftime(“Today is %A”)     # “Today is Saturday”
> time.strftime(“%d of %B, %Y”)    # “2 of January, 2016”
> time.strftime(“Unix time is %s”) # “Unix time is 1449336630”

Date and Time are important parts of an application and the above examples should provide a core understanding of how we can utilise them. Be sure to check out the documentations.

Leave a comment