How do you convert Unix epoch time into real time in C#? (Epoch beginning 1/1/1970)
Use the method DateTimeOffset.ToUnixTimeMilliseconds() It returns the number of milliseconds that have elapsed since 1970-01-01T00:00:00.000Z.
This is only supported with Framework 4.6 or higher
var EPOCH = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
It's well documented here DateTimeOffset.ToUnixTimeMilliseconds
The other way out is to use the following
long EPOCH = DateTime.UtcNow.Ticks - new DateTime(1970, 1, 1,0,0,0,0).Ticks;
To get the EPOCH with seconds only you may use
var Epoch = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;
and convert the Epoch
to DateTime
with the following method
private DateTime Epoch2UTCNow(int epoch)
{
return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(epoch);
}