Kyle
Kyle

Reputation: 35

JavaScript Date converting to the wrong Java Date

I have a JavaScript Date object,Thu Jul 02 2015 00:00:00 GMT-0400 (Eastern Standard Time), which is passed to a Java method that stores this date in a Java Date object. But the Java date object shows this date as Wed Jul 01 23:00:00 CDT 2015. How can I get the correct conversion from JavaScript Date to Java Date?

Note: This only happens when i have my PC set to Eastern Standard Time and the clock is set to around 9 AM. Other than that, if i set my PC's timezone back to Central Standard Time, then this is no longer an issue.

Update

The number of milliseconds from the epoch to 07/02/15 is 1435809600000. If I take these milliseconds and create a JS Date object like so, new Date(1435809600000), I get this: Thu Jul 02 2015 00:00:00 GMT-0400 (Eastern Standard Time). But when i try to create a Java Date object, new Date(1435809600000), I get: Wed Jul 01 23:00:00 CDT 2015

Upvotes: 0

Views: 1350

Answers (3)

gfelisberto
gfelisberto

Reputation: 1723

Try with:

String fromJavascript = "Thu Jul 02 2015 00:00:00 GMT-0400";

SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'Z", Locale.US);

try {
    Date converted = sdf.parse(fromJavascript);

    System.out.println(converted);
} catch (ParseException e) {            
    e.printStackTrace();
}

The converted object should contain the correct date. What gets printed will depend on the TZ of the running client. But that you can control when presenting.

Upvotes: 0

DaBaer
DaBaer

Reputation: 204

The problem is most definitely the Local TZ of the client. Maybe this post can help, by removing the localization from your DateTime object. How to ignore user's time zone and force Date() use specific time zone

Upvotes: 0

Davide Lorenzo MARINO
Davide Lorenzo MARINO

Reputation: 26926

The best solution is to send the data as long (milliseconds from 1/1/1970) and construct a new Date in java starting from it.

Javascript code

var date = ... // date is of type Date
var dateMillis = date.getTime();  // Milliseconds long representing the date

Java code

long dateMillis = .... // Milliseconds long representing the date
Date date = new Date(dateMillis);

Upvotes: 2

Related Questions