0

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

Kyle
  • 35
  • 9

3 Answers3

2

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);
Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
  • I thought this would work too. I updated the OP explaining the results of attempting what you suggested. – Kyle Jul 16 '15 at 16:02
  • 1
    The problem is that you are using different Standard Time in java and in javascript. If you use the same it should work. – Davide Lorenzo MARINO Jul 16 '15 at 16:05
  • I selected this. I realized that the client is using the EST timezone, and the server is using the CST timezone. – Kyle Jul 16 '15 at 16:33
0

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

Community
  • 1
  • 1
DaBaer
  • 204
  • 1
  • 7
0

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.

gfelisberto
  • 1,655
  • 11
  • 18