Home  >  Article  >  Backend Development  >  How to get Unix timestamp in C#

How to get Unix timestamp in C#

WBOY
WBOYforward
2023-09-15 18:49:02791browse

如何在 C# 中获取 Unix 时间戳

Unix timestamps are mainly used in Unix operating systems. But it helps everyone operating system as it represents time in all time zones.

Unix timestamp represents time in seconds. The Unix epoch begins on the 1st January 1970.

Thus, a Unix timestamp is the number of seconds between a specific date

Example

Use DateTime.Now.Subtract to get the Unix timestamp().Total seconds 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

Use TimeSpan structure method to obtain Unix timestamp

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

The above is the detailed content of How to get Unix timestamp in C#. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete