This post will discuss how to find the total number of elapsed milliseconds since the epoch in C#. The epoch or Unix time represents the number of seconds that have elapsed since 1970-01-01T00:00:00Z (1st Jan 1970, 12:00 AM UTC).

1. Using ToUnixTimeMilliseconds() method

To find the number of milliseconds elapsed since the epoch, you can invoke the DateTimeOffset.ToUnixTimeMilliseconds() method. This method is available in .NET Framework 4.6 and later. It works by converting the current instance to Universal Time Coordinated (UTC), before calculating the milliseconds in its Unix time.

This sample creates an instance of the DateTimeOffset class that is set to the current date and time and invokes the ToUnixTimeMilliseconds() method to get Unix time as UTC.

Download  Run Code

 
There is a similar method in the DateTimeOffset class – TounixTimeInMillisecSeconds() – which can be used to get the number of seconds that have elapsed since the epoch.

Download  Run Code

 
If you already have a DateTime instance, you can cast it to DateTimeOffset object, and call the TounixTimeInMillisecSeconds() or ToUnixTimeMilliseconds() upon it to get the Unix timestamp.

Download  Run Code

2. Using TimeSpan.TotalMilliseconds Property

Another option is to get the current date and time in UTC using DateTime.UtcNow, and find its difference with another DateTime object representing the epoch time of 1970-01-01T00:00:00Z. Then you can use the TimeSpan.TotalMilliseconds property to get the milliseconds value from the resultant TimeSpan object. Here’s an example of how you could achieve that.

Download  Run Code

 
You may want to use TimeSpan.TotalSeconds over TimeSpan.TotalMilliseconds to get the Unix timestamp in seconds.

Download  Run Code

 
The DateTime class defines a constant, UnixEpoch, which represents the point in time when Unix time is equal to 0 (January 1, 1970, 00:00:00.0000000 UTC). This can be used over new DateTime(1970, 1, 1), as illustrated below:

Download  Run Code

3. Using TimeSpan.TicksPerMillisecond property

Alternatively, you can get the number of ticks representing the current date and time in UTC, and find its difference with the number of ticks representing the Unix timestamp. Since there are 10000 ticks in 1 millisecond, as defined by the constant TimeSpan.TicksPerMillisecond, you need to divide the difference by it to get the elapsed milliseconds since the epoch.

Download  Run Code

 
Similarly, there are 10000000 ticks in 1 second. To get the elapsed seconds since the epoch, you can use constant TimeSpan.TicksPerSecond:

Download  Run Code

That’s all about finding the total number of elapsed milliseconds since the epoch in C#.