Overview
This code demonstrates how to convert between Unix time (Epoch time) and System.DateTime. This code was previously mentioned in my Protrack API post.
Definition
As described by Wikipedia, Unix time (also known as POSIX time or UNIX Epoch time) is a system for describing a point in time. It is the number of seconds that have elapsed since 00:00:00 Thursday, 1 January 1970, Coordinated Universal Time (UTC), minus leap seconds.
Unix time is represented as a signed 32-bit integer, although a 64-bit timestamp has been introduced later.
Code
The following code converts Unix time to System.DateTime and vice versa:
- static class UnixTimeHelper {
- /// <summary>
- /// Converts DateTime to Unix time.
- /// </summary>
- public static long ToUnixTime(this DateTime time) {
- var totalSeconds = (long)(time.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
- return totalSeconds;
- }
- /// <summary>
- /// Converts Unix time to DateTime.
- /// </summary>
- public static DateTime ToDateTime(long unixTime) {
- return new DateTime(1970, 1, 1).Add(TimeSpan.FromSeconds(unixTime));
- }
- }

Join the conversation! Your thoughts help the community grow.