Convert NativeDate Nashorn to java.util.Date

When returning Javascript objects Datein Java using Nashorn in Java 8, for example:

ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("nashorn");
Object js = engine.eval("new Date();");

On the following attempts, I get exceptions:

  • Date javaDate = (Date)js;

    jdk.nashorn.api.scripting.ScriptObjectMirror cannot be cast to java.util.Date

  • Date javaDate = js.to(Date.class);

    Cannot cast jdk.nashorn.internal.objects.NativeDate to java.util.Date

  • Date javaDate = (Date)ScriptUtils.convert(js.to(NativeDate.class), Date.class);

    Cannot cast jdk.nashorn.internal.objects.NativeDate to java.util.Date

Back with Rhino I just used context.jsToJava(nativeDateObj, Date.class);.

Any ideas on how I can actually use this NativeDate when it returns to Java?

PS If I do js.toString (), it will give me "[Date 2012-01-01T19: 00: 00.000Z]". I guess I could regex make it out ... but why-oh-why ...

+4
source share
3 answers

Rolled back the JavaScript object on jdk.nashorn.api.scripting.ScriptObjectMirror, then you can access its properties in the form of a map.

ScriptObjectMirror jsDate = (ScriptObjectMirror) engine.eval("new Date();")
long timestampLocalTime = (long) (double) jsDate.callMember("getTime"); 
// yes, js date returns timestamp in local time so you need to adjust it... ;)
int timezoneOffsetMinutes = (int) (double) jsDate.callMember("getTimezoneOffset");
// java.util.Date construcctor utilizes UTC timestamp
Date jDate = new Date(timestampLocalTime + timezoneOffsetMinutes * 60 * 1000);

: http://cr.openjdk.java.net/~sundar/jdk.nashorn.api/8u20/javadoc/jdk/nashorn/api/scripting/ScriptObjectMirror.html

, "JavaScript-" Java, "overlay" javascript. . :

public interface JsDateWrapper {
    long getTime();
    int getTimezoneOffset();
    // ...
}

Object jso = engine.eval("new Date();");
JsDateWrap jsDate = ((Invocable) engine).getInterface(jso, JsDateWrapper.class);
Date jDate = new Date(jsDate.getTime() + jsDate.getTimezoneOffset() * 60 * 1000);
+6

:

retValue = new Date(value.to(Long.class));
+1

same problem here, resolved with:

ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("nashorn");
Object js = engine.eval("new java.util.Date();");
0
source

All Articles