How to Get the Unix Timestamp in C#

How to get the unix timestamp in C#

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)

C#: Get unix timestamp with microseconds

You just need to subtract the Unix epoch (1970-01-01T00:00:00Z) from the DateTimeOffset to get a TimeSpan, then get the microseconds from that by dividing the total number of ticks by 10:

using System;

public static class DateTimeOffsetExtensions
{
private static readonly DateTimeOffset UnixEpoch =
new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);

public static long ToUnixTimeMicroseconds(this DateTimeOffset timestamp)
{
TimeSpan duration = timestamp - UnixEpoch;
// There are 10 ticks per microsecond.
return duration.Ticks / 10;
}
}

public class Test
{
static void Main()
{
DateTimeOffset now = DateTimeOffset.UtcNow;
Console.WriteLine(now.ToUnixTimeMicroseconds());
}
}

How can I convert a Unix timestamp to DateTime and vice versa?

Here's what you need:

public static DateTime UnixTimeStampToDateTime( double unixTimeStamp )
{
// Unix timestamp is seconds past epoch
DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
dateTime = dateTime.AddSeconds( unixTimeStamp ).ToLocalTime();
return dateTime;
}

Or, for Java (which is different because the timestamp is in milliseconds, not seconds):

public static DateTime JavaTimeStampToDateTime( double javaTimeStamp )
{
// Java timestamp is milliseconds past epoch
DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
dateTime = dateTime.AddMilliseconds( javaTimeStamp ).ToLocalTime();
return dateTime;
}

C# Convert from and back to Unix timestamp

The problem is in .DateTime fragment in the line

    var date = DateTimeOffset.FromUnixTimeSeconds(timestamp).DateTime;

According to reference source

private DateTime ClockDateTime {
get {
// Here we lose Timezone (Offset) - it just added to m_dateTime
// Kind is Unspecified, that's why we can restore the fact
// Offset == 0 and we actually have UTC datetime
return new DateTime((m_dateTime + Offset).Ticks, DateTimeKind.Unspecified);
}
}

public DateTime DateTime {
get {
return ClockDateTime;
}
}

.Net creates for .DateTime property a new DateTime instance with Kind == DateTimeKind.Unspecified, so you lose timezone (now Offset from DateTimeOffset is just added to DateTime).

In order to correct the test put .UtcDateTime instead of .DateTime:

    var date = DateTimeOffset.FromUnixTimeSeconds(timestamp).UtcDateTime; 

How to generate a UTC Unix Timestamp in C#

private double ConvertToTimestamp(DateTime value)
{
//create Timespan by subtracting the value provided from
//the Unix Epoch
TimeSpan span = (value - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime());

//return the total seconds (which is a UNIX timestamp)
return (double)span.TotalSeconds;
}

Parsing unix time in C#

Simplest way is probably to use something like:

private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, 
DateTimeKind.Utc);

...
public static DateTime UnixTimeToDateTime(string text)
{
double seconds = double.Parse(text, CultureInfo.InvariantCulture);
return Epoch.AddSeconds(seconds);
}

Three things to note:

  • If your strings are definitely of the form "x.y" rather than "x,y" you should use the invariant culture as shown above, to make sure that "." is parsed as a decimal point
  • You should specify UTC in the DateTime constructor to make sure it doesn't think it's a local time.
  • If you're using .NET 3.5 or higher, you might want to consider using DateTimeOffset instead of DateTime.


Related Topics



Leave a reply



Submit