How to convert Java.Util.Date to System.DateTime
android, datetime
Solution
`java.util.Date` has a `getTime()` method, which returns the date as a millisecond value. The value is the number of milliseconds since Jan. 1, 1970, midnight GMT.
With that knowledge, you can construct a `System.DateTime`, that matches this value like so:
public DateTime FromUnixTime(long unixTimeMillis)
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return epoch.AddMilliseconds(unixTimeMillis);
}
(method taken from this answer)
Problem
In Xamarin.Android, you work with both .NET and Java. I get a return value of Java.Util.Date, I then need to input that same value as a parameter that only takes System.DateTime This is how I currently do it ``` public static DateTime ConvertJavaDateToDateTime(Date date) { var a = date.ToGMTString(); var b = date.ToLocaleString(); var c = date.ToString(); DateTime datetime = DateTime.ParseExact(date.ToGMTString(), "dd MMM yyyy HH:mm:ss 'GMT'", CultureInfo.InvariantCulture); return datetime; } ``` However on the first 9 days of any month, I only get 1 digit for the day, and the DateTime.ParseExact function is looking for dd (i.e. 2 digits for the day). a is a string with value "1 Sep 2014 14:32:25 GMT" b is a string with value "1 Sep 2014 16:32:25" c is a string with value "Mon Sep 01 16:32:25 EET 2014" I wish I could find a simple, quick, reliable and consistent solution for this problem :D