Unix Timestamp in C#

.NET counts in ticks internally, so epoch conversion goes through DateTimeOffset. Use it rather than DateTime, which does not reliably carry an offset.

Need to convert one value rather than write code? Use the interactive converter — it handles every unit and time zone without leaving your browser.

Current Unix timestamp

using System;

DateTimeOffset.UtcNow.ToUnixTimeSeconds();       // 1710050400
DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();  // 1710050400000

Timestamp to date

long ts = 1710050400;

var utc = DateTimeOffset.FromUnixTimeSeconds(ts);
Console.WriteLine(utc.ToString("o"));            // round-trip ISO 8601

var tz  = TimeZoneInfo.FindSystemTimeZoneById("Asia/Kolkata");
var local = TimeZoneInfo.ConvertTime(utc, tz);
Console.WriteLine(local);

Date to timestamp

var dto = new DateTimeOffset(2024, 3, 10, 6, 0, 0, TimeSpan.Zero);
dto.ToUnixTimeSeconds();                         // 1710050400

DateTimeOffset.Parse("2024-03-10T06:00:00Z").ToUnixTimeSeconds();

Cross-platform zone IDs

// .NET 6+ accepts IANA ids on Windows too, but older runtimes need
// the Windows name ("India Standard Time"). TimeZoneConverter bridges both.
var tz = TimeZoneInfo.FindSystemTimeZoneById(
    OperatingSystem.IsWindows() ? "India Standard Time" : "Asia/Kolkata");

Pitfalls specific to C#

  • DateTime.Kind is a trap: an Unspecified value converts using local rules without warning. Prefer DateTimeOffset throughout.
  • The .NET epoch for ticks is year 1, not 1970 — never compute epochs by subtracting ticks by hand.

Rules that apply in every language

  1. Store UTC, display local. Keep the instant in UTC everywhere in your system and convert only at the point a human reads it.
  2. Name the unit in the identifier. expires_at_ms rather than expires_at costs nothing and prevents the single most common timestamp bug.
  3. Never trust a client clock. Stamp anything security-relevant on the server. See the note on clock skew.
  4. Use 64-bit time. Anything still storing seconds in a signed 32-bit field breaks in January 2038 — see the Year 2038 problem.

The same task in other languages

Frequently asked questions

How do I get the current Unix timestamp in C#?

Use the snippet in the "Current Unix timestamp" section above. C# works in ticks (100 ns) natively, so converting to another unit is a multiplication or an integer division away.

How do I convert a Unix timestamp to a date in C#?

The "Timestamp to date" snippet above shows the idiomatic approach, including how to render the result in a specific time zone rather than whatever zone the machine happens to be set to.

Does C# handle time zones and daylight saving correctly?

Yes, provided you pass an explicit zone rather than relying on the system default. The gotchas listed on this page cover the specific ways C# makes that easy to get wrong.