In Ruby, the Date and Time classes are part of the Ruby standard library and are used to work with dates and times. Here’s a brief overview of each class along with some examples:
1. Date Class: The Date class in Ruby is used to represent dates without times. It provides various methods for performing date-related calculations.
Example 1: Creating a Date object
require 'date' # Create a Date object for today's date today = Date.today puts today # Output: YYYY-MM-DD format for the current date
Example 2: Performing Date Calculations
require 'date' today = Date.today future_date = today + 7 # Add 7 days to today's date puts future_date # Output: YYYY-MM-DD for the date 7 days from today
2. Time Class: For representing both dates and times in Ruby, use the Time class. The methods it offers for working with hours, minutes, seconds, and fractions of a second make it more versatile than the Date class.
Example 1: Creating a Time object
require 'time' # Create a Time object for the current date and time current_time = Time.now puts current_time # Output: Current date and time in a specific format
Example 2: Performing Time Calculations
require 'time' current_time = Time.now future_time = current_time + 3600 # Add 1 hour (3600 seconds) to the current time puts future_time # Output: Current time + 1 hour