HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcsharpCritical

How to get the Unix timestamp in C#

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howtimestampthegetunix

Problem

I have had a look around Stack Overflow and even looked at some of the suggested questions and none seem to answer: How do you get a Unix timestamp in C#?

Solution

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

e.g.

Int32 unixTimestamp = (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;


DateTime.UtcNow can be replaced with any DateTime object that you would like to get the unix timestamp for.

There is also a field, DateTime.UnixEpoch, which is very poorly documented by MSFT, but may be a substitute for new DateTime(1970, 1, 1)

Code Snippets

Int32 unixTimestamp = (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;

Context

Stack Overflow Q#17632584, score: 743

Revisions (0)

No revisions yet.