C# Unix 时间戳代码片段
C# 示例,涵盖当前纪元秒、毫秒、DateTimeOffset 转换、ISO 8601 输出,以及从日期字符串解析时间戳。
C# timestamp basics
Modern C# should use DateTimeOffset for Unix timestamp work. DateTimeOffset.UtcNow.ToUnixTimeSeconds() returns Unix seconds, and ToUnixTimeMilliseconds() returns JavaScript-compatible milliseconds.
Converting DateTimeOffset values
Use FromUnixTimeSeconds or FromUnixTimeMilliseconds to convert epoch values into DateTimeOffset. Keep storage in UTC and format with the round-trip O format when you need an ISO 8601 string.
C# production notes
DateTimeOffset is usually safer than DateTime for timestamp work because it keeps an offset attached to the value. Store UTC instants for comparisons and persistence, then convert to a local timezone only for display. Be careful when integrations say epoch time without naming seconds or milliseconds.
- Use DateTimeOffset.UtcNow.ToUnixTimeSeconds() for standard Unix seconds
- Use ToUnixTimeMilliseconds() for JavaScript-compatible values
- Use FromUnixTimeSeconds() when reading API values documented as seconds
- Use the O format for round-trip ISO 8601 strings in logs and JSON
Frequently checked C# details
- Should timestamp code use DateTime or DateTimeOffset?
- Prefer DateTimeOffset for Unix timestamp work because it preserves offset context. It also exposes direct Unix seconds and milliseconds helpers.
- What does the O format do?
- The O format writes a round-trip ISO 8601 value. It is useful for logs, JSON, and tests where the exact instant should survive parsing.
- How do I verify a C# conversion?
- Convert the value back with DateTimeOffset.FromUnixTimeSeconds or FromUnixTimeMilliseconds, format it with O, and compare that UTC output with your expected timestamp before saving the value.