Web Design that taps into the haromny and vision of your dreams.

Converting To and From Unix Timestamps

Converting to and from Unix Timestamps and DateTime objects

Written By on in C#

139 words, estimated reading time 1 minutes.

From time to time it is necessary to convert to and from Unix timestamps, mainly when dealing with system interoperability. These timestamps are an accurate measure of time from a given point and have a simple data type.

Unix time is defined as the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970.

These two functions will convert a .Net DateTime into a Unix timestamp and vice versa.

public static DateTime ConvertFromUnixTimestamp(ulong timestamp)
    DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
    return origin.AddSeconds(timestamp);
public static double ConvertToUnixTimestamp(DateTime? date = null)
    DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
    TimeSpan diff = (date ?? DateTime.Now) - origin;
    return Convert.ToDouble(Math.Floor(diff.TotalSeconds));

Year 2038 Problem

There are however limitations to the current implementation of Unix timestamps. On 32-bit data types, the date time 03:14:07 UTC on 19 January 2038 represents the maximum value an integer can hold. One second after this and the time will rollover, back to 1970. This is the second coming of the millennium bug. Hopefully, by then, every system will have been upgraded to 64-bit long data types.

Last updated on: Wednesday 21st June 2017



There are no comments for this post. Be the first!


Leave a Reply

Your email address will not be published.

If you find something abusive or that does not comply with our terms or guidelines please flag it as inappropriate.

Copyright © 2001-2018 Tim Trott, all rights reserved. Web Design by Azulia Designs

This web page is licensed for your personal, private, non-commercial use only.

Disclaimer, Privacy & LegalSitemapContact Me