Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the unix timestamp in C#

I have had look around stackoverflow, and even looked at some of the suggested questions and none seem to answer, how do you get a unix timestamp in C#?

like image 421
bizzehdee Avatar asked Jul 13 '13 17:07

bizzehdee


People also ask

How do I get the current unix timestamp in C#?

You get a unix timestamp in C# by using DateTime. UtcNow and subtracting the epoch time of 1970-01-01.

What is unix timestamp value?

In computing, Unix time (also known as Epoch time, Posix time, seconds since the Epoch, Unix timestamp or UNIX Epoch time) is a system for describing a point in time. It is the number of seconds that have elapsed since the Unix epoch, excluding leap seconds. The Unix epoch is 00:00:00 UTC on 1 January 1970.

What is timestamp in C++?

timestamp, a C++ code which prints the current YMDHMS date as a timestamp. This is useful when documenting the run of a program. By including a timestamp, the output of the program will always contain a clear indication of when it was created.


1 Answers

As of .NET 4.6, there is DateTimeOffset.ToUnixTimeSeconds.


This is an instance method, so you are expected to call it on an instance of DateTimeOffset. You can also cast any instance of DateTime, though beware the timezone. To get the current timestamp:

DateTimeOffset.Now.ToUnixTimeSeconds() 

To get the timestamp from a DateTime:

DateTime foo = DateTime.Now; long unixTime = ((DateTimeOffset)foo).ToUnixTimeSeconds(); 
like image 109
Bob Avatar answered Nov 09 '22 20:11

Bob