0

Working With Dates And Times In Ruby

Last Updated on

Without using any Ruby gems, Time is the class we can use when working with dates and times. It represents the number of seconds with fraction since the Epoch, January 1, 1970, 00:00 UTC. The Time class treats GMT (Greenwich Mean Time) and UTC (Coordinated Universal Time) as equivalent. GMT is the older way of referring to these baseline times but persists in the names of calls on POSIX systems.

Since Ruby 1.9.2, Time implementation uses a signed 63-bit integer, Bignum or Rational, to store the number of nanoseconds since the Epoch which can represent 1823-11-12 to 2116-02-20. When Bignum or Rational is used (before 1823, after 2116, under nanosecond), Time works slower as when integer is used.

Creating Dates and Times

There are several ways to create dates and times in Rust.

The example produces the following output.

Components Of Date and Time

The following is a working example to get the current date and time in Ruby. It also displays the date components – day, month, etc.

The example produces the following output.

Timezones and Daylight Savings Time

We can also use the Time object to get the information associated with Timezones and daylight savings. It is helpful when working with zones, UTC offsets, etc.

Working With Formatting Times and Dates

There are various ways to work with dates and times in various formats. Here are a few.

The codes will output the following result.

Formatting Directives

We can use the following directives with the method Time.strftime in Ruby.

DirectiveDescription
%aThe abbreviated weekday name (Sun).
%AThe full weekday name (Sunday).
%bThe abbreviated month name (Jan).
%BThe full month name (January).
%cThe preferred local date and time representation.
%dDay of the month (01 to 31).
%HHour of the day, 24-hour clock (00 to 23).
%IHour of the day, 12-hour clock (01 to 12).
%jDay of the year (001 to 366).
%mMonth of the year (01 to 12).
%MMinute of the hour (00 to 59).
%pMeridian indicator (AM or PM).
%SSecond of the minute (00 to 60).
%UWeek number of the current year, starting with the first Sunday as the first day of the first week (00 to 53).
%WWeek number of the current year, starting with the first Monday as the first day of the first week (00 to 53).
%wDay of the week (Sunday is 0, 0 to 6).
%xPreferred representation for the date alone, no time.
%XPreferred representation for the time alone, no date.
%yYear without a century (00 to 99).
%YYear with century.
%ZTime zone name.
%%Literal % character.

Time Arithmetic

We can perform date and time arithmetic in Ruby, as follows.

The codes will produce the following result.

Karl San Gabriel

Karl San Gabriel

Professional Software Developer