This post will discuss how to find the total number of milliseconds in C# that have elapsed since the Unix epoch. The Unix epoch is the time 00:00:00 UTC on 1st January 1970.

1. Using DateTimeOffset.ToUnixTimeMilliseconds() method

The DateTimeOffset.ToUnixTimeMilliseconds() method returns the total number of milliseconds that have elapsed since the epoch. This can be called as the following to get milliseconds in UTC:

Download  Run Code

 
Alternatively, we can use the DateTimeOffset constructor, which takes a DateTime object representing the current UTC date and time.

Download  Run Code

2. Using TimeSpan.TotalMilliseconds Property

The idea is to get a TimeSpan object representing the date difference between the current date and epoch. Then we can use the TimeSpan.TotalMilliseconds property to get the total number of milliseconds.

 
This can be done using either DateTimeOffset or DateTime. Both approaches are discussed below.

1. Using DateTimeOffset

Download  Run Code

2. Using DateTime

Download  Run Code

That’s all about getting the number of milliseconds since Unix epoch in C#.