How to convert a Unix timestamp to milliseconds in C#

By FoxLearn 1/3/2025 1:23:22 AM   92
In C#, to get the current Unix timestamp in milliseconds, you can use the following code:

How to get Unix time in milliseconds in C#?

The FromUnixTimeMilliseconds() method in C# converts a Unix timestamp, expressed in milliseconds since January 1, 1970, to a DateTimeOffset value.

// c# unix timestamp milliseconds
DateTimeOffset value = DateTimeOffset.FromUnixTimeMilliseconds(100000);

// Display the time
Console.WriteLine("DateTimeOffset is {0}", value); // DateTimeOffset is 01/01/1970 00:01:40 +00:00

You can also convert the Unix timestamp to milliseconds in C# as shown below.

using System;

class Program
{
    static void Main()
    {
        // Get the current UTC time
        DateTime currentUtcTime = DateTime.UtcNow;
        
        // Unix epoch start time (1970-01-01)
        DateTime unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
        
        // Calculate the Unix timestamp in milliseconds
        long unixTimestampMilliseconds = (long)(currentUtcTime - unixEpoch).TotalMilliseconds;
        
        // Print the Unix timestamp in milliseconds
        Console.WriteLine(unixTimestampMilliseconds);
    }
}

In this example:

  • DateTime.UtcNow gives the current UTC time.
  • A DateTime representing the Unix epoch (1970-01-01 00:00:00 UTC) is created.
  • The difference between the current time (DateTime.UtcNow) and the Unix epoch is calculated using TimeSpan.
  • The TotalMilliseconds property of the TimeSpan gives the total milliseconds.
  • This value is cast to long to represent the Unix timestamp in milliseconds.