Nashorn NativeDate转换为java.util.Date

时间:2014-08-19 14:23:29

标签: java javascript date nashorn

在Java 8上使用Nashorn将Javascript Date对象返回给Java时,如下所示:

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

通过以下尝试,我获得例外:

  1. Date javaDate = (Date)js;

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

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

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

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

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

  4. 回到Rhino我只是使用context.jsToJava(nativeDateObj, Date.class);

    任何想法,当它返回Java时,我如何实际构建这个NativeDate?

    P.S。如果我执行js.toString(),那么它会给我" [Date 2012-01-01T19:00:00.000Z]"。我想我可以正则表达式解析...但为什么 - 哦 - 为什么......

3 个答案:

答案 0 :(得分:6)

jdk.nashorn.api.scripting.ScriptObjectMirror上投放返回的JavaScript对象,然后您就可以在"类似地图"中访问其属性方式。

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);

答案 1 :(得分:1)

这里遇到同样的问题,解决了:

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

答案 2 :(得分:1)

我在我的项目中这样做:

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