How to Convert JavaScript Date to Date in Java?

Viewed 58601

I need to convert JsDate to java.util.Date. I searched but I couldn't find anything. So could you help me with this problem?

Edit: I do this conversion process on GWT screen. I have Datepicker on screen and it gives me JsDate value when I use it's getValue() method. So I'm supposed to put this value into the property of an object which has Date type.

ObjectName.setDate(PickerName.getValue());

I hope my edit will be more clear.

Edit2:

This line is the solution of my problem:

myObject.setDate(new Date((long) myPicker.getValue().getTime()));
7 Answers

ISO 8601 and java.time

ISO 8601 is the international standard for date and time including date and time formats. About any programming language has support for it, including both JavaScript and Java.

In JavaScript produce a string in ISO 8601 format using Date.toISOString(). We don’t need any formatter.

  var d = new Date();
  var n = d.toISOString();
  console.log(n);

The result is somewhat human readable as long as you remember that it’s in UTC, denoted by the trailing Z.

In Java parse the string using Instant.parse(). We don’t need to specify any formatter here either.

    String stringFromJavaScript = "2021-07-12T05:54:03.365Z";
    Instant inst = Instant.parse(stringFromJavaScript);
    System.out.println(inst);

Output:

2021-07-12T05:54:03.365Z

The question asked for a java.util.Date for the result from a date picker. We should avoid using java.util.Date for this both because despite the name a Date does not represent a date and because the Date class is poorly designed and long outdated. For a date without time of day a LocalDate is appropriate:

    LocalDate date = inst.atZone(ZoneId.systemDefault()).toLocalDate();
    System.out.println(date);

In my time zone the output was:

2021-07-12

The conversion is time zone dependent and will only be correct if the default time zone of the JVM (or which time zone you pass to atZone()) is the same as used by the date picker.

If you do need a Date for a legacy API not yet upgraded to java.time:

    Date oldfashionedDate = Date.from(inst);
    System.out.println(oldfashionedDate);

Mon Jul 12 07:54:03 CEST 2021

Links

JS Date -- new Date() Wed Aug 14 2019 14:54:38 GMT+0530 (India Standard Time)

Java Date -- new Date().toISOString() "2019-08-14T09:25:50.136Z"

Related