ruby
  1. ruby-date-time

Ruby Date & Time

Syntax

Ruby has a built-in Date and Time class that can be used to handle all kinds of date and time-related operations. It comes with a set of methods and operators to work with dates and times.

date = Date.new(2022, 1, 1)             # creates a Date object for Jan 1, 2022
time = Time.new(2022, 1, 1, 12, 0, 0)  # creates a Time object for noon of Jan 1, 2022

Example

require 'date'

# create a Date object for today
today = Date.today

# print the day of the month
puts today.day

# print the month name
puts today.strftime("%B")

# create a Time object for now
now = Time.now

# print the hour and minute
puts now.strftime("%H:%M")

Output

14
October
16:30

Explanation

The above example uses the Date and Time classes to:

  1. Create a Date object for today's date using Date.today method.
  2. Print the day of the month using day method.
  3. Print the month name using strftime method with %B format.
  4. Create a Time object for the current time using Time.now method.
  5. Print the current hour and minute using strftime method with %H:%M format.

Use

Here are some common use cases for the Date and Time classes:

  • Calculate durations between two dates or times
  • Work with time zones and daylight saving time
  • Parse and format dates and times
  • Validate and manipulate dates and times
  • Convert between different date and time formats

Important Points

  • The Date class represents a date (year, month, and day) and has methods to add or subtract days, weeks, months, or years.
  • The Time class represents a point in time (hour, minute, second, and fractional seconds) and has methods to add or subtract seconds, minutes, hours, or days.
  • Dates and times can be formatted using the strftime method, which takes a formatting string as argument.
  • The DateTime class is a subclass of Date and Time, and represents a date and time with fractional seconds and timezone information.

Summary

In this tutorial, we learned about the Date and Time classes in Ruby and how to use them to perform various date and time-related operations. We also looked at some important points to keep in mind while working with dates and times.

Published on: