在 Ruby 中,日期和时间处理主要由 Date 和 Time 类来完成。以下是关于 Ruby 日期和时间的基本操作和特性:

日期
require 'date'

# 获取当前日期
current_date = Date.today
puts current_date

# 创建特定日期
custom_date = Date.new(2023, 12, 25)
puts custom_date

# 获取日期的年、月、日
year = custom_date.year
month = custom_date.month
day = custom_date.day

# 日期格式化为字符串
formatted_date = custom_date.strftime("%Y-%m-%d")
puts formatted_date

时间
# 获取当前时间
current_time = Time.now
puts current_time

# 创建特定时间
custom_time = Time.new(2023, 12, 25, 12, 0, 0)
puts custom_time

# 获取时间的年、月、日、时、分、秒
year = custom_time.year
month = custom_time.month
day = custom_time.day
hour = custom_time.hour
minute = custom_time.min
second = custom_time.sec

# 时间格式化为字符串
formatted_time = custom_time.strftime("%Y-%m-%d %H:%M:%S")
puts formatted_time

时间间隔
# 计算日期间隔
date1 = Date.new(2023, 12, 25)
date2 = Date.new(2023, 12, 31)
difference_in_days = (date2 - date1).to_i
puts difference_in_days

# 计算时间间隔
time1 = Time.new(2023, 12, 25, 12, 0, 0)
time2 = Time.new(2023, 12, 31, 18, 30, 0)
difference_in_seconds = (time2 - time1).to_i
puts difference_in_seconds

时间操作
# 在日期上进行操作
future_date = current_date + 7  # 7天后的日期
past_date = current_date - 3    # 3天前的日期

# 在时间上进行操作
future_time = current_time + (60 * 60 * 24)  # 24小时后的时间
past_time = current_time - (60 * 60 * 3)     # 3小时前的时间

这些只是 Ruby 中日期和时间处理的一部分功能,还有更多的方法和选项可供使用。


转载请注明出处:http://www.pingtaimeng.com/article/detail/13434/Ruby