How to get the Unix timestamp in C#


A Unix timestamp is mainly used in Unix operating systems. But it is helpful for all operating systems because it represents the time of all time zones.

Unix Timestamps represent the time in seconds. The Unix epoch started on 1st January 1970.

So, Unix Timestamp is the number of seconds between a specific date

Example

to get the Unix Timestamp Using DateTime.Now.Subtract().TotalSeconds Method

class Program{
   static void Main(string[] args){
      Int32 unixTimestamp = (Int32)(DateTime.Now.Subtract(new
      DateTime(1970, 1, 1))).TotalSeconds;
      Console.WriteLine("The Unix Timestamp is {0}", unixTimestamp);
      Console.ReadLine();
   }
}

Output

1596837896

Example

to get the Unix Timestamp Using DateTimeOffset.Now.ToUnixTimeSeconds() Method

class Program{
   static void Main(string[] args){
      var unixTimestamp = DateTimeOffset.Now.ToUnixTimeSeconds();
      Console.WriteLine("The Unix Timestamp is {0}.", unixTimestamp);
      Console.ReadLine();
   }
}

Output

1596819230.

Example

to Get the Unix Timestamp Using TimeSpan Struct Methods

class Program{
   static void Main(string[] args){
      TimeSpan epochTicks = new TimeSpan(new DateTime(1970, 1, 1).Ticks);
      TimeSpan unixTicks = new TimeSpan(DateTime.Now.Ticks) - epochTicks;
      Int32 unixTimestamp = (Int32)unixTicks.TotalSeconds;
      Console.WriteLine("The Unix Timestamp is {0}.", unixTimestamp);
      Console.ReadLine();
   }
}

Output

1596839083

Updated on: 19-Aug-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements