How to Convert Epoch Time in C#

How do you convert epoch time in C#?

UPDATE 2020

You can do this with DateTimeOffset

DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(epochSeconds);
DateTimeOffset dateTimeOffset2 = DateTimeOffset.FromUnixTimeMilliseconds(epochMilliseconds);

And if you need the DateTime object instead of DateTimeOffset, then you can call the DateTime property

DateTime dateTime = dateTimeOffset.DateTime;


Original answer

I presume that you mean Unix time, which is defined as the number of seconds since midnight (UTC) on 1st January 1970.

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

public static DateTime FromUnixTime(long unixTime)
{
return epoch.AddSeconds(unixTime);
}

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# Epoch DateTime conversion

A double only has enough precision to hold down to milliseconds. If you want more precision, you will have to use DateTime.Ticks which is a long. A long is an exact value, it won't change.

If you want milliseconds, then as @Magnetron points out, there are built-in methods for that. Above all, and this is general advice, if you need an exact value, don't use double or float types.

C# Epoch time to date and timezone convertion


Database date is: 1398891600 = 2014-05-01

X Website date is: 1398902400000 = 2014-05-01

EpochConverter.com gives me the following results:

1398891600000 -> Wed, 30 Apr 2014 21:00:00 GMT

1398902400000 -> Thu, 01 May 2014 00:00:00 GMT

So your code seems to be consistent with EpochConverter.com.

With regards to timezones, I would make sure all dates are stored/retrieved using UTC. This will save you a lot of headaches when it comes to converting to/from different timezones. In this case, assuming the epoch was stored relative to a UTC date, you would simply do the following:

DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(Convert.ToDouble(epochdate));

You can then use the following if you need to display a local time to the end user:

utcDate.ToLocalTime();

Convert epoch/unix to Datetime

That timestamp (1365151714493) is in milliseconds, not seconds. You'll need to divide by 1000 or use AddMilliseconds instead. If it's treated as seconds, it's a date some 43,259 (rough calculation) years in the future. This is beyond the range of DateTime which maxes out at the year 10000, thus throwing the ArgumentOutOfRangeException.

public static DateTime? ConvertUnixTimeStamp(string unixTimeStamp)
{
return new DateTime(1970, 1, 1, 0, 0, 0).AddMilliseconds(Convert.ToDouble(unixTimeStamp));
}

You may also want to consider forcing it to GMT as V4Vendetta suggested. In addition, if you expect to have a mix of formats (seconds OR milliseconds) perhaps a quick size check on the parsed value might be prudent.

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)

Converting Epoch timestamp to DateTime

As explained by this answer, the Chrome timestamp is not equal to Unix epoch time. This is why you're not getting the results you expect from such methods. It's actually microseconds since the 1st Jan, 1601 (as opposed to Unix epoch time's seconds since 1st Jan, 1970).

You can test your WebKit timestamp here, where you'll see it returns Tuesday, 6 August 2019 10:57:48 (UTC).

So to convert this in code, we should first subtract the difference between 1970 and 1601 (in microseconds) and then divde the value by 1 million to get seconds (C# solution):

public static DateTime ConvertWebKitTime(long webkitEpoch)
{
const long epochDifferenceMicroseconds = 11644473600000000; // difference in microseconds between 1601 and 1970
var epoch = (webkitEpoch - epochDifferenceMicroseconds) / 1000000; // adjust to seconds since 1st Jan 1970
return DateTimeOffset.FromUnixTimeSeconds(epoch).UtcDateTime; // convert to datetime
}

Converting DateTime to EPOCH time is returning a new Date

You need to ensure that you're comparing times in the correct timezones. I recommend converting both to UTC:

TimeSpan t = dt.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);


Related Topics



Leave a reply



Submit