Seconds since the Unix epoch in C#
A question about how to get the “C style representation” out of a DateTime came over an internal alias recently. Turns out the person needed the number of seconds since the Unix epoch. Not too bad to do with the DateTime class…
TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1));
int timestamp = (int) t.TotalSeconds;
But notice I did use the UtcNow property to ensure that the timestamp is the same regardless of what timezone this code is being run it. If you are doing something timestamp related and you are NOT using UtcNow, chances are you have bug.