C# Tips

C# Tip Article

How to get unix timestamp in C#

The unix time stamp is the number of seconds between a particular date and the Unix Epoch(1970/1/1) at UTC. In C#, this timestamp can be obtained by simple time calculation as below:

// get unix timestamp
int timestamp = (int)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
//

Technically unix timestamp will stop working on 2038/1/19 because of 32bit overflow.

Tick property in DateTime represents 100 ns (nanoseconds). There are 10,000 ticks in a millisecond.

nanosecond :  0.000000001 secs (1 / 1,000,000,000)
1 tick     :  0.0000001 secs   (1 / 10,000,000)  
microsecond:  0.000001 secs    (1 / 1,000,000)
millisecond:  0.001 secs       (1 / 1,000)

To get the ticks since Unix Epoch(1970/1/1), use this:

long ticks = (DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).Ticks;

To get the total milliseconds since Unix Epoch(1970/1/1), use one of these expressions:

// (1) Use TotalMilliseconds
double ms = (DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalMilliseconds;

// (2) Calculate from Ticks
long ticks = (DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).Ticks;
double ms2 = ticks / 10000;

// (3) If you want integer only
long ms3 = (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalMilliseconds;