How to Convert JavaScript Date to Date in Java?

The best way of dates conversion is using time in milliseconds, UTC. Both JS Date object and java.util.Date class support conversion to milliseconds (getTime()) and instantiating from milliseconds (using constructor).


You can create a java.util.Date object from the 'time since epoch' value of the JS Date

javascript

var d = new Date().getTime();

java

// get value from client (ajax, form, etc), and construct in Date object

long valueFromClient = ...

Date date = new Date(valueFromClient);

String formatted = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);

If people like me are forced to parse a JS-formatted date string (as the result of (new Date()).toString() in JavaScript), here is the SimpleDateFormat spec I used:

DateFormat jsfmt = new SimpleDateFormat("EE MMM d y H:m:s 'GMT'Z (zz)");

If you have control of the producer of the dates, I concur that using timestamps or at least .toUTCString() is definitely more robust.