Ruby Snippets

Ruby Unix 时间戳代码片段

Ruby 示例,用于获取 Unix 秒、推导毫秒、将时间戳转换为 Time 对象、格式化 UTC 输出,以及解析日期字符串。

Current Unix timestamp (seconds)
Time.now.to_i
Current Unix timestamp (milliseconds)
(Time.now.to_f * 1000).round
Time from Unix timestamp
Time.at(1700000000)
Time in specific timezone
require "time"
Time.at(1700000000).utc.strftime("%Y-%m-%d %H:%M:%S")

# With tzinfo gem:
require "tzinfo"
tz = TZInfo::Timezone.get("America/New_York")
tz.utc_to_local(Time.at(1700000000).utc)
Formatted string
Time.at(1700000000).strftime("%Y-%m-%d %H:%M:%S")
Timestamp from Time
require "time"
Time.parse("2023-11-15T06:13:20Z").to_i

Ruby 时间戳基础

Ruby 的 Time.now.to_i 返回 Unix 秒。当你需要秒的小数,或想为期望 JavaScript 风格时间戳的 API 计算毫秒时,使用 Time.now.to_f。

转换并格式化 Ruby 的 Time

用 Time.at(timestamp) 从 Unix 秒创建一个 Time 对象。当你需要不依赖机器本地时区的稳定输出时,在格式化之前调用 utc。

Ruby 生产注意事项

Ruby 的 Time 方法很简洁,但时区默认值在笔记本、服务器和后台 worker 之间可能不同。把持久化的时间戳保持为 Unix 秒或 UTC 字符串,然后在表现层应用应用程序时区。解析用户输入时,包含偏移或时区,以免错误地猜测夏令时规则。

  • Unix 秒用 Time.now.to_i
  • 毫秒值用 (Time.now.to_f * 1000).round
  • 稳定的 UTC 输出用 Time.at(seconds).utc
  • Time.parse 仅用于包含时区或偏移的字符串

FAQ

Time.now.to_i 返回毫秒吗?
不。Time.now.to_i 返回整数 Unix 秒。如果你需要秒的小数部分或想得到毫秒,请使用 Time.now.to_f。
为什么在格式化前调用 utc?
utc 使输出与机器的本地时区无关。这对日志、API 负载和测试预期很有帮助。
如何验证 Ruby 时间戳?
使用 Time.at(seconds).utc.iso8601,并在把值写入任务、API 或数据库之前,把结果与期望的 UTC 时刻比较。