Overview
C# developers should usually use DateTimeOffset for Unix timestamp conversion. It provides FromUnixTimeSeconds, FromUnixTimeMilliseconds, ToUnixTimeSeconds, and ToUnixTimeMilliseconds methods.
This guide focuses on practical implementation choices: how values should be stored, how they should cross API boundaries, and where developers most often introduce timezone or precision bugs. The safest pattern is to keep the stored value unambiguous, document the unit, and format the date only when it reaches a human-facing interface.
When to use it
Use DateTimeOffset for APIs, logs, database values, and cross-timezone conversion. Convert to local time only when rendering for a user.
For production systems, also consider how the value will be indexed, logged, serialized, and read by other teams. A timestamp field that is obvious in one programming language can become ambiguous when it is consumed by JavaScript, SQL, mobile clients, or third-party integrations.
Developer examples
Use examples like this as a starting point, then adapt the timezone and precision to your application contract.
var instant = DateTimeOffset.FromUnixTimeSeconds(1717243200);
Console.WriteLine(instant.UtcDateTime);
long now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
Common pitfalls
DateTime.Kind can be ambiguous. DateTimeOffset is clearer for instants that cross system boundaries.
Most timestamp bugs come from hidden assumptions: local time treated as UTC, seconds treated as milliseconds, formatted strings parsed without offsets, or narrow integer columns copied from old examples. Add tests for boundary dates and document the expected unit beside every external timestamp field.
FAQ
Should I use DateTime or DateTimeOffset?
DateTimeOffset is usually safer for timestamp conversion because it preserves offset context.
How do I get milliseconds?
Use ToUnixTimeMilliseconds or FromUnixTimeMilliseconds.