Epoch in C#

A common requirement in programs is getting the number of seconds, milliseconds, or nanoseconds since the Unix epoch. Here’s how to do it in C#.

using System;

class Program
{
    static void Main()
    {
        // Use DateTime.UtcNow to get the current UTC time
        DateTime now = DateTime.UtcNow;
        Console.WriteLine(now);

        // Convert to seconds, milliseconds, and nanoseconds since Unix epoch
        DateTimeOffset unixEpoch = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
        TimeSpan timeSinceEpoch = now - unixEpoch.UtcDateTime;

        Console.WriteLine(timeSinceEpoch.TotalSeconds);
        Console.WriteLine(timeSinceEpoch.TotalMilliseconds);
        Console.WriteLine(timeSinceEpoch.Ticks * 100); // Ticks to nanoseconds

        // You can also convert integer seconds or nanoseconds
        // since the epoch into the corresponding DateTime.
        Console.WriteLine(unixEpoch.AddSeconds(timeSinceEpoch.TotalSeconds));
        Console.WriteLine(unixEpoch.AddTicks(timeSinceEpoch.Ticks));
    }
}

To run the program, compile and execute it:

$ csc Program.cs
$ mono Program.exe
2023-05-10 12:34:56.789012 +00:00
1683720896.7890120
1683720896789.0120
168372089678901200
5/10/2023 12:34:56 PM
5/10/2023 12:34:56 PM

In C#, we use DateTime.UtcNow to get the current UTC time. To calculate the time since the Unix epoch, we create a DateTimeOffset representing the Unix epoch and subtract it from the current time.

The TimeSpan class provides properties like TotalSeconds and TotalMilliseconds for easy conversion. For nanoseconds, we multiply Ticks by 100 (as each tick is 100 nanoseconds).

To convert back from seconds or nanoseconds to DateTime, we use the AddSeconds and AddTicks methods on the Unix epoch DateTimeOffset.

Next, we’ll look at another time-related task: time parsing and formatting.