Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Wednesday, February 4, 2015

C# - Convert Java Time (in Milliseconds) to Windows Time

Assume you have a frontend built with C# and a backend built with Java. In a grid view you want to display some data from a database table and one column uses numeric format to store date/time values.

If you simply do like the following way, you will get wrong answer.
  DateTime dateTime = DateTime.FromFileTime(javaTime);

  return dateTime.ToString("yyyy-MM-dd HH:mm:ss");

To get correct answer, use this code:

private static DateTime WINDOWS_EPOCH = new DateTime(1601, 1, 1, 0, 0, 0);
private static DateTime JAVA_EPOCH = new DateTime(1970, 1, 1, 0, 0, 0);

public static String FromJavaTime(long javaTime, string timeFormat)
{
  long epochDiff = (JAVA_EPOCH.ToFileTimeUtc() - WINDOWS_EPOCH.ToFileTimeUtc()) / TimeSpan.TicksPerMillisecond;

  DateTime dateTime = DateTime.FromFileTime((javaTime + epochDiff) * TimeSpan.TicksPerMillisecond);

  return dateTime.ToString(timeFormat);
}

Then if you run FromJavaTime(1420621059959, "yyyy-MM-dd HH:mm:ss"), you will get "2015-01-07 16:57:39".



Create a Successful Online Store at Bigcommerce! Try it Free Now!