Get the Unix Epoch time in one line of C#

int epoch = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;

An alternate (possibly faster) method might be:

long time = (DateTime.UtcNow.Ticks - 621355968000000000) / 10000000;

Although the second method does conform to the Unmaintainable Code standard, I’d recommend sticking with the first method unless you really need those extra nanoseconds.

Leave a Reply