📜  Ruby 整数时间函数与示例(1)

📅  最后修改于: 2023-12-03 14:47:09.543000             🧑  作者: Mango

Ruby 整数时间函数与示例

在 Ruby 中,我们可以使用整数来表示秒数、分钟数、小时数等时间单位,并使用相应的函数进行时间计算。

Time 类

首先,让我们了解 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_iTime#to_f 函数来获取时间戳。

timestamp = current_time.to_i
puts timestamp # 输出当前时间的时间戳,如 "1630415746"
时间戳转换成 Time 对象

如果我们有了时间戳,可以使用 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

Time.now.to_i 函数可以获取当前时间的时间戳,与上文中介绍的函数效果相同。

timestamp = Time.now.to_i
puts timestamp
Integer#minutes、Integer#hours、Integer#days

在整数后面加上诸如 minuteshoursdays 等单位,可以将该整数解释为以这个单位为基础的时间长度。

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
Integer#since、Integer#ago

在整数后面加上 sinceago,可以将该整数解释为距离当前时间多长时间之前或之后的时间点。

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
Integer#day、Integer#month、Integer#year

在整数后面加上 daymonthyear,可以将该整数解释为日、月、年。

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