Thursday, December 3, 2009

Converting a Java Unix Epoch Time to a C# Date

I do a lot of coding that involves passing serialized objects between C# and Java based applications. When in Java I tend to work with dates as a long. In Java, a date can be represented as a long that is the number of milliseconds since the unix epoch which is defined as:

"Unix time, or POSIX time, is a system for describing points in time, defined as the number of seconds elapsed since midnight proleptic Coordinated Universal Time (UTC) of January 1, 1970, not counting leap seconds." (http://en.wikipedia.org/wiki/Unix_time)

If you have a date object in java, you just call the date.GetTime() function to return that value.

.Net does not work well with this and I just found myself coding happily along until i hit this and realized i had to write this handy little C# function i now share with the world:


  DateTime ConvertEpochToDate(long epochMS)
        {
            DateTime disco = new System.DateTime(1970, 01, 01, 00, 00, 00, 00);
            return disco.AddMilliseconds(Timestamp);
        }


You can see, we add the milliseconds i have to a new datetime object that has been initialized to the unix epoch


1 comment: