Learn how to convert a unixtime to an instance of the DateTime class and a DateTime class to a unixtime in C#

Unix time is basically the number of seconds that have passed since 1/1/1970 00:00:00 (UTC). In order to convert a specific date and time to a Unix time value we will need to subtract the date above from the date we want to convert to Unix time. Although you may not believe it, in .NET c# doesn't include a standard way to convert this unit to a datetime with a default method, instead you will need to write some extra logic to convert between these values.

In this article, we'll show you how to convert an unixtime to an instance of DateTime in C#.

A. Unixtime to DateTime

In order to convert an unix time to a DateTime instance in C#, you will just need to add the given timestamp as milliseconds to a DateTime instance with the following date:  1/1/1970 00:00:00, as shown in the following snippet, the method UnixTimeToDateTime expects as first argument the long representation of the unix timestamp and returns the modified date:

/// <summary>
/// Convert Unix time value to a DateTime object.
/// </summary>
/// <param name="unixtime">The Unix time stamp you want to convert to DateTime.</param>
/// <returns>Returns a DateTime object that represents value of the Unix time.</returns>
public DateTime UnixTimeToDateTime(long unixtime)
{
    System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
    dtDateTime = dtDateTime.AddMilliseconds(unixtime).ToLocalTime();
    return dtDateTime;
}

The following example shows how to to use the method and the output:

// Outputs: 21-Mar-19 10:32:53 PM
Console.WriteLine(UnixTimeToDateTime(1553225573655));

B. DateTime to Unixtime

If you are working in the creation of some kind of API that requires the unix timestamp format, you can easily convert a DateTime instance to the mentioned format with the following method:

/// <summary>
/// Convert a DateTime to a unix timestamp
/// </summary>
/// <param name="MyDateTime">The DateTime object to convert into a Unix Time</param>
/// <returns></returns>
public long DateTimeToUnix(DateTime MyDateTime)
{
    TimeSpan timeSpan = MyDateTime - new DateTime(1970, 1, 1, 0, 0, 0);

    return (long)timeSpan.TotalSeconds;
}

The following example shows how to use the method and the output:

// Prints "1553299673"
Console.WriteLine(DateTimeToUnix(DateTime.UtcNow));

Happy coding !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors