In this post I am going to show you how to convert from a Unix timestamp to DateTime in C#. Afterwards I am going to show you how to convert in the opposite direction, from DateTime to a Unix timestamp. During this, I will shortly go over considerations to take when working with time in relation to time zones and daylight saving time.
Unix timestamp to DateTime
When converting from a timestamp to DateTime there are two things to consider; is the timestamp in seconds or milliseconds, and do you want to set the DateTime to your local time or use UTC time?
My recommendation regarding local or UTC time is to use UTC time, as you then avoid issues when working across time zones or daylight saving time, giving you a common time standard.
My implementation of conversion from a Unix timestamp to DateTime looks as follows:
public DateTime UnixSecondsToDateTime(long timestamp, bool local = false) { var offset = DateTimeOffset.FromUnixTimeSeconds(timestamp); return local ? offset.LocalDateTime : offset.UtcDateTime; } public DateTime UnixMillisecondsToDateTime(long timestamp, bool local = false) { var offset = DateTimeOffset.FromUnixTimeMilliseconds(timestamp); return local ? offset.LocalDateTime : offset.UtcDateTime; }
You are able to get the UTC DateTime from a local DateTime and vice versa. Therefore, these methods won’t lock you to one or the other, although the code cohesion will deteriorate if you return a local DateTime and then grab the UTC DateTime from the object.
If you don’t want to make the decision as to whether you want to utilize the local or UTC DateTime in your conversion methods, you can implement the following methods instead.
public DateTime UnixSecondsToDateTime(long timestamp) { return DateTimeOffset.FromUnixTimeSeconds(timestamp).DateTime; } public DateTime UnixMillisecondsToDateTime(long timestamp) { return DateTimeOffset.FromUnixTimeMilliseconds(timestamp).DateTime; }
DateTime to Unix timestamp
Compared to converting from a Unix timestamp to DateTime, when doing it the other way around you don’t have to consider time zones.
My implementation of methods for converting from a DateTime to a timestamp, either in seconds or milliseconds, looks as follows:
public long DateTimeToUnixSeconds(DateTime time) { return ((DateTimeOffset)time).ToUnixTimeSeconds(); } public long DateTimeToUnixMilliseconds(DateTime time) { return ((DateTimeOffset)time).ToUnixTimeMilliseconds(); }