Get number of milliseconds since Unix epoch in C#
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:
1 2 3 4 5 6 7 8 9 10 11 12 |
using System; public class Example { public static void Main() { DateTimeOffset now = DateTimeOffset.UtcNow; long unixTimeMilliseconds = now.ToUnixTimeMilliseconds(); Console.WriteLine(unixTimeMilliseconds); } } |
Alternatively, we can use the DateTimeOffset
constructor, which takes a DateTime
object representing the current UTC date and time.
1 2 3 4 5 6 7 8 9 10 11 12 |
using System; public class Example { public static void Main() { DateTime now = DateTime.UtcNow; long unixTimeMilliseconds = new DateTimeOffset(now).ToUnixTimeMilliseconds(); Console.WriteLine(unixTimeMilliseconds); } } |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System;using System; public class Example { public static void Main() { DateTimeOffset eposh = DateTimeOffset.UnixEpoch; DateTimeOffset now = DateTimeOffset.UtcNow; TimeSpan ts = now.Subtract(eposh); double unixTimeMilliseconds = ts.TotalMilliseconds; Console.WriteLine(unixTimeMilliseconds); } } |
2. Using DateTime
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; public class Example { public static void Main() { DateTime epoch = DateTime.UnixEpoch; DateTime now = DateTime.UtcNow; TimeSpan ts = now.Subtract(epoch); double unixTimeMilliseconds = ts.TotalMilliseconds; Console.WriteLine(unixTimeMilliseconds); } } |
That’s all about getting the number of milliseconds since Unix epoch in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)