Android Date to C# long DateTime Ticks

I have an Android App and a C# mvc Web API. I want to sent a Date (and some other data) with a HttpPOST from the Android App to the WebAPI.

Right now I use long ticks = myDate.getTime(); in Android and DateTime date = new DateTime(ticks); in C#.

With the Date 2014-06-11 00:00:00 my ticks in Android is 1402459200000 and my DateTime in C# is 0001-01-02​T14:57:25 PM

How to properly convert a Date to long and from long to DateTime, from Android to C#?

PS: I could send a String date in Android, then convert it to a DateTime date and convert that to long ticks in C#, but since I need a long C# for a method I can't change the parameters of, I would prefer to just send the correct long from Android directly.

Jon Skeet
people
quotationmark

Date in Java doesn't have ticks - it has milliseconds. Additionally, the epoch for Date is the Unix epoch (1970-01-01) whereas the epoch for DateTime is 0001-01-01. You need to take both of these into account - as well as the fact that the epoch of Date is in UTC, whereas the epoch of DateTime varies depending on kind. You probably want something like:

private static readonly UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0,
                                                 DateTimeKind.Utc);

...

long millis = ...;
DateTime dateFromJavaApp = UnixEpoch + Timespan.FromMilliseconds(millis);

Or you could use my Noda Time library which makes this (and many other things) simpler:

long millis = ...;
Instant instant = Instant.FromMillisecondsSinceUnixEpoch(millis);

people

See more on this question at Stackoverflow