Epoch and Date Time Conversion in C# or C Sharp

C# or C Sharp is a simple, modern, general-purpose, object-oriented programming language. It is intended for use in developing software components suitable for deployment in distributed environments. It is more suitable for writing applications for both the hosted and embedded systems. The C# provided date time methods from DateTime to handle epoch or Unix timestamp conversion into human readable dates or can convert human readable dates to Unix timestamp.

Here we will explain C# Date/Time functions to get current epoch or Unix timestamp, convert timestamp to date and convert date to epoch or Unix timestamp.

Get current epoch or Unix timestamp in C#

We will use the DateTimeOffset instance method ToUnixTimeSeconds() to get the current timestamp.

DateTimeOffset.Now.ToUnixTimeSeconds()

We can also get the current timestamp from a DateTime: DateTime foo = DateTime.Now;
long unixTime = ((DateTimeOffset)foo).ToUnixTimeSeconds();


Convert epoch or Unix timestamp to date in C#

We will use the method FromUnixTimeSeconds() to convert the epoch or timestamp to readable date format.

var dateTime = DateTimeOffset.FromUnixTimeSeconds(1550962800);


Convert date to epoch or unix timestamp in C#

We can convert human readable date to timestamp using ToUnixTimeMilliseconds() method.

var dateTime = new DateTime(2021, 02, 21, 22, 0, 0, DateTimeKind.Utc);
var dateWithOffset = new DateTimeOffset(dateTime).ToUniversalTime();
long timestamp = dateWithOffset.ToUnixTimeMilliseconds();



More about date time in C#