Z
ZHANK
标准库与工具

日期时间处理

Time/Date/DateTime、strftime 格式化、时间运算、ActiveSupport

日期时间处理

Ruby 内置 TimeDateDateTime 三个时间类。Rails 的 ActiveSupport 更是时间操作的瑞士军刀。

学完本章你将: 掌握 Time/Date/DateTime、strftime 格式化、时间运算。


Time

ruby
now = Time.now        # 当前时间
time = Time.new(2024, 7, 23, 14, 30, 0)

# 格式化
now.strftime("%Y-%m-%d %H:%M:%S")  # "2024-07-23 14:30:00"
now.strftime("%Y年%m月%d日")       # "2024年07月23日"

# 时间运算
tomorrow = now + 86400     # +1 天(秒)
yesterday = now - 86400

# 常用方法
now.year      # 2024
now.month     # 7
now.day       # 23
now.wday      # 2(星期几,0=周日)
now.monday?   # false

Date / DateTime

ruby
require "date"

date = Date.today
date = Date.new(2024, 7, 23)
date.next_day        # 明天
date.prev_month      # 上个月

# 时间差
(Date.today - Date.new(2024, 1, 1)).to_i  # 距离元旦多少天

ActiveSupport 时间(Rails)

ruby
3.days.ago            # 3 天前
2.weeks.from_now      # 2 周后
1.month.since(now)    # 1 个月后
Time.current          # 时区感知的当前时间