Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Java.Util.Date to System.DateTime

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

like image 307
Mohamed Heiba Avatar asked Jul 04 '14 13:07

Mohamed Heiba


People also ask

Does Java Util date have time?

No time data is kept. In fact, the date is stored as milliseconds since the 1st of January 1970 00:00:00 GMT and the time part is normalized, i.e. set to zero. Basically, it's a wrapper around java. util.

What is Java Util date format?

Date format conversion yyyy-mm-dd to mm-dd-yyyy.

What is the difference between Java Util date and Java sql date?

sql. Date just represent DATE without time information while java. util. Date represents both Date and Time information.


Video Answer


1 Answers

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)

like image 109
Dennis Avatar answered Sep 21 '22 18:09

Dennis