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#.
This is what I've got so far:
public Double CreatedEpoch
{
get
{
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime();
TimeSpan span = (this.Created.ToLocalTime() - epoch);
return span.TotalSeconds;
}
set
{
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime();
this.Created = epoch.AddSeconds(value);
}
}
DateTime to UNIX timestamp:
Here's what you need:
Or, for Java (which is different because the timestamp is in milliseconds, not seconds):
I needed to convert a timeval struct (seconds, microseconds) containing
UNIX time
toDateTime
without losing precision and haven't found an answer here so I thought I just might add mine:"UTC does not change with a change of seasons, but local time or civil time may change if a time zone jurisdiction observes daylight saving time (summer time). For example, UTC is 5 hours ahead of (that is, later in the day than) local time on the east coast of the United States during winter, but 4 hours ahead while daylight saving is observed there."
So this is my code:
you can call UnixTime.UnixTimeToDateTime(double datetime))
The latest version of .NET (v4.6) has added built-in support for Unix time conversions. That includes both to and from Unix time represented by either seconds or milliseconds.
DateTimeOffset
:DateTimeOffset
to Unix time in seconds:DateTimeOffset
:DateTimeOffset
to Unix time in milliseconds:Note: These methods convert to and from a UTC
DateTimeOffset
. To get aDateTime
representation simply use theDateTimeOffset.UtcDateTime
orDateTimeOffset.LocalDateTime
properties: