There is this example code, but then it starts talking about millisecond / nanosecond problems.
The same question is on MSDN, Seconds since the Unix epoch in C#<
DateTime to UNIX timestamp:
public static double DateTimeToUnixTimestamp(DateTime dateTime)
{
return (TimeZoneInfo.ConvertTimeToUtc(dateTime) -
new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc)).TotalSeconds;
}
I found the right answer just by comparing the conversion to 1/1/1970 w/o the local time adjustment;
DateTime date = new DateTime(2011, 4, 1, 12, 0, 0, 0);
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0);
TimeSpan span = (date - epoch);
double unixTime =span.TotalSeconds;
Here's what you need:
public static DateTime UnixTimeStampToDateTime( double unixTimeStamp )
{
// Unix timestamp is seconds past epoch
System.DateTime dtDateTime = new DateTime(1970,1,1,0,0,0,0,System.DateTimeKind.Utc);
dtDateTime = dtDateTime.AddSeconds( unixTimeStamp ).ToLocalTime();
return dtDateTime;
}
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
System.DateTime dtDateTime = new DateTime(1970,1,1,0,0,0,0,System.DateTimeKind.Utc);
dtDateTime = dtDateTime.AddMilliseconds( javaTimeStamp ).ToLocalTime();
return dtDateTime;
}
System.DateTimeOffset.Now.ToUnixTimeSeconds()
var dt = DateTime.Now;
var unixTime = ((DateTimeOffset)dt).ToUnixTimeSeconds();
// 1510396991
var dt = DateTimeOffset.FromUnixTimeSeconds(1510396991);
// [11.11.2017 10:43:11 +00:00]
Be careful, if you need precision higher than milliseconds!
.NET (v4.6) methods (e.g. FromUnixTimeMilliseconds) don't provide this precision.
AddSeconds and AddMilliseconds also cut off the microseconds in the double.
These versions have high precision:
Unix -> DateTime
public static DateTime UnixTimestampToDateTime(double unixTime)
{
DateTime unixStart = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
long unixTimeStampInTicks = (long) (unixTime * TimeSpan.TicksPerSecond);
return new DateTime(unixStart.Ticks + unixTimeStampInTicks, System.DateTimeKind.Utc);
}
DateTime -> Unix
public static double DateTimeToUnixTimestamp(DateTime dateTime)
{
DateTime unixStart = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
long unixTimeStampInTicks = (dateTime.ToUniversalTime() - unixStart).Ticks;
return (double) unixTimeStampInTicks / TimeSpan.TicksPerSecond;
}