📅  最后修改于: 2023-12-03 14:47:09.543000             🧑  作者: Mango
在 Ruby 中,我们可以使用整数来表示秒数、分钟数、小时数等时间单位,并使用相应的函数进行时间计算。
首先,让我们了解 Ruby 中用于处理时间的 Time
类。该类是 Ruby 标准库中内置的类之一,提供了一系列用于获取/设置时间、计算时间间隔等功能。
获取当前时间可以使用 Time.now
函数,该函数返回当前时间的 Time
对象。
current_time = Time.now
puts current_time # 输出形如 "2021-08-31 11:55:46 +0800" 的字符串
时间戳是指从 1970 年 1 月 1 日 00:00:00 UTC 起至现在所经过的秒数。在 Ruby 中,我们可以使用 Time#to_i
或 Time#to_f
函数来获取时间戳。
timestamp = current_time.to_i
puts timestamp # 输出当前时间的时间戳,如 "1630415746"
如果我们有了时间戳,可以使用 Time.at
函数将其转换成对应的 Time
对象。
timestamp = 1630415746
time_from_timestamp = Time.at(timestamp)
puts time_from_timestamp # 输出与当前时间相差若干秒的时间字符串
Time
类还提供了一些函数,用于计算时间间隔,包括:
Time#-
:计算两个时间之间的时间差,以秒为单位。结果为正数时代表前者晚于后者,否则相反。Time#+
:将一个时间对象加上若干秒,返回新的时间对象。start_time = Time.now
sleep(3) # 睡眠 3 秒
end_time = Time.now
time_diff = end_time - start_time # 计算结束时间与开始时间之间的时间差,单位为秒
puts "程序运行了 #{time_diff.round(2)} 秒" # 四舍五入保留两位小数
new_time = start_time + 60 # 将开始时间加上 60 秒,返回新的时间对象
puts new_time
除了使用 Time
类处理时间,还可以使用 Ruby 中的整数时间函数来方便地进行时间计算。
Time.now.to_i
函数可以获取当前时间的时间戳,与上文中介绍的函数效果相同。
timestamp = Time.now.to_i
puts timestamp
在整数后面加上诸如 minutes
、hours
、days
等单位,可以将该整数解释为以这个单位为基础的时间长度。
now = Time.now
later = now + 3.minutes # 3 分钟后的时间
tomorrow = now + 1.days # 1 天后的时间
next_month = now + 1.months # 1 个月后的时间
puts later
puts tomorrow
puts next_month
在整数后面加上 since
或 ago
,可以将该整数解释为距离当前时间多长时间之前或之后的时间点。
now = Time.now
three_seconds_ago = 3.seconds.ago # 3 秒之前的时间
two_hours_since = 2.hours.since # 2 小时之后的时间
puts three_seconds_ago
puts two_hours_since
在整数后面加上 day
、month
、year
,可以将该整数解释为日、月、年。
today = Time.now
yesterday = 1.day.ago # 昨天的时间
last_month = 1.month.ago # 上个月的时间
last_year = 1.year.ago # 去年的时间
puts yesterday
puts last_month
puts last_year