How to get the Unix timestamp in C#

CsharpServer Side ProgrammingProgramming

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
raja
Published on 19-Aug-2020 13:25:25
Advertisements