Runar Ovesen Hjerpbakk

Software Philosopher

Get milliseconds from Unix epoch in C#

I needed a method in C# to get the number of milliseconds since the start of Unix time.

Unix time (also known as POSIX time or UNIX Epoch time) is a system for describing a point in time, defined as the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970, minus the number of leap seconds that have taken place since then.

This is the DateTime extension method I came up with:

public static long MillisecondsFromUnixEpoch(this DateTime dateTime) =>
   (long)dateTime.Subtract(DateTime.MinValue.AddYears(1969)).TotalMilliseconds;

Example of usage:

var fromUnixEpoch = timeStamp.MillisecondsFromUnixEpoch();