Ruby Dates
Published Jul 30, 2021Updated Sep 9, 2021
Contribute to Docs
In Ruby, date- and time-specific data are handled by two classes:
DateDateTime
In order to use these classes, import the date module:
require("date")
Syntax
To create a new Date object, use .new():
# With 1 argumentmyDate = Date.new(year)# With 2 argumentsmyDate = Date.new(year, month)# With 3 argumentsmyDate = Date.new(year, month, day)myDate = Date.new(2021, 07, 30)puts myDate # Output: 2021-07-30
To create a new DateTime object, use .new():
require("date")myDateTime = DateTime.new(year, month, day, hour, minute, second, offset)myDateTime = DateTime.new(2021, 07, 30, 13, 46, 45, "+4")puts myDateTime # Output: 2021-07-30T13:46:45+04:00
To create a new DateTime object set to this very moment, use .now():
puts DateTime.now # Output: 2021-07-30T13:48:56-04:00
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Ruby on Codecademy
- Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
- Includes 34 Courses
- With Professional Certification
- Beginner Friendly.115 hours
- Learn to program in Ruby, a flexible and beginner-friendly language used to create sites like Codecademy.
- Beginner Friendly.9 hours