Ruby Unix 時間戳程式碼片段
Ruby 範例,用於取得 Unix 秒、推導毫秒、將時間戳轉換為 Time 物件、格式化 UTC 輸出,以及解析日期字串。
Ruby timestamp basics
Ruby's Time.now.to_i returns Unix seconds. Use Time.now.to_f when you need fractional seconds or want to calculate milliseconds for APIs that expect JavaScript-style timestamps.
Converting and formatting Ruby Time
Use Time.at(timestamp) to create a Time object from Unix seconds. Call utc before formatting when you need stable output that does not depend on the machine's local timezone.
Ruby production notes
Ruby's Time methods are concise, but timezone defaults can vary between laptops, servers, and background workers. Keep persisted timestamps in Unix seconds or UTC strings, then apply the application timezone at the presentation layer. When parsing user input, include the offset or timezone so daylight saving rules are not guessed incorrectly.
- Use Time.now.to_i for Unix seconds
- Use (Time.now.to_f * 1000).round for millisecond values
- Use Time.at(seconds).utc for stable UTC output
- Use Time.parse only with strings that include a timezone or offset
Frequently checked Ruby details
- Does Time.now.to_i return milliseconds?
- No. Time.now.to_i returns whole Unix seconds. Use Time.now.to_f if you need fractional seconds or want to derive milliseconds.
- Why call utc before formatting?
- utc makes the output independent of the machine's local timezone. That is helpful for logs, API payloads, and test expectations.
- How do I verify a Ruby timestamp?
- Use Time.at(seconds).utc.iso8601 and compare the result with the expected UTC moment before writing the value to a job, API, or database.