Home > Backend Development > C#.Net Tutorial > How to get Unix timestamp in C#

How to get Unix timestamp in C#

WBOY
Release: 2023-09-15 18:49:02
forward
877 people have browsed it

如何在 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();
   }
}
Copy after login

Output

1596837896
Copy after login

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();
   }
}
Copy after login

Output

1596819230.
Copy after login

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();
   }
}
Copy after login

Output

1596839083
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template