Unix Timestamp in C#

C# uses DateTimeOffset.UtcNow for timezone-safe timestamps. ToUnixTimeSeconds() and ToUnixTimeMilliseconds() give you Unix timestamps directly — no math required.

Ad

Code Examples

Current timestamp (seconds)

long seconds = DateTimeOffset.UtcNow.ToUnixTimeSeconds();

DateTimeOffset is timezone-aware and the recommended type for Unix timestamps in modern C#. Returns long.

Current timestamp (milliseconds)

long ms = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();

Returns milliseconds since epoch as long. Available since .NET 4.6 / .NET Core 1.0.

Convert timestamp to DateTimeOffset

var dto = DateTimeOffset.FromUnixTimeSeconds(timestamp);

Converts a Unix timestamp (seconds) back to a DateTimeOffset in UTC. Use .LocalDateTime to convert to local time.

Using DateTime (legacy — avoid for timestamps)

var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
long seconds = (long)(DateTime.UtcNow - epoch).TotalSeconds;

The old manual approach before .NET 4.6. Included for reference — prefer DateTimeOffset.ToUnixTimeSeconds() in new code.

Format as ISO 8601

var dto = DateTimeOffset.FromUnixTimeSeconds(timestamp);
string iso = dto.ToString("o"); // Round-trip format

The "o" format specifier produces ISO 8601 / RFC 3339 output: 2024-02-22T00:00:00.0000000+00:00.

Note

Always use DateTimeOffset instead of DateTime for Unix timestamps — DateTimeOffset carries timezone offset information, preventing local-time bugs. DateTime.Kind = Unspecified (the default) is a common source of subtle timestamp errors in C# apps.

Ad

Need to convert a specific timestamp? Use the live converter — paste any epoch value and see the human-readable date instantly.

← Open the converter