The POSIX time, or Unix time, is the number of seconds elapsed from the midnight of January 1st 1970 in UTC coordinates.
This timestamp is used in all *nix languages; probably you will never need to use a Unix timestamp in .NET, but if you have to interact with other application or sites, maybe built in PHP or Java, you will probably have to deal with it.
But .NET doesn't have a method to convert a Unix timestamp to a DateTime and viceversa (or I didn't find it), so I had to implement it.
static DateTime ConvertFromUnixTimestamp(double timestamp) { DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0); return origin.AddSeconds(timestamp); } static double ConvertToUnixTimestamp(DateTime date) { DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0); TimeSpan diff = date - origin; return Math.Floor(diff.TotalSeconds); }
The first method converts a Unix timestamp to its DateTime equivalent, and the second takes a DateTime and convert it to the Unix time.
And in order to get the current timestamp
ConvertToUnixTimestamp(DateTime.UtcNow)
Just a little note on the Unix time: this timestamp is implemented in most systems as a signed 32-bit integer, so can represent only dates in a the range −2,147,483,648 to +2,147,483,647, which means that on January 19th, 2038 the timestamp will overflow, bringing the date back to December 13th, 1901. This is known as Year 2038 problem. Hopefully most of the application we are building now will not last that long.
Ref : http://codeclimber.net.nz/archive/2007/07/10/convert-a-unix-timestamp-to-a-.net-datetime.aspx
http://hassakarn.com/2012/10/10/convert-datetime-to-unix-timestamp-in-c/
not a developer, I usually convert unix timestamp to human readable date using this free online tool: http://unixresources.net/
ReplyDelete