Using Rhino instead of ScriptEngine to run Javascript code in Java

拈花ヽ惹草 提交于 2019-12-01 15:39:38

In the script that is executed by the JavaScript engine, you just need to calculate the value you want using new Date(dateString).getTime() (you could also use "var date = new Date(dateString); date.getTime()";). You should not store the result inside a variable.

I also made two additions to your method:

  • To convert the result of the evaluation to a String, you should use Context.toString(obj). Since here, the result is actually a number, we can use directly Context.toNumber(obj), which returns a double, and cast it to long.
  • I added a finally block which exits from the Context.

Working code:

private static long parseDateUsingRhino(String dateInUnknownFormat) {
    Context mozillaJsContext = Context.enter();
    try {
        Scriptable scope = mozillaJsContext.initStandardObjects();
        String script = "new Date('" + dateInUnknownFormat + "').getTime()";
        Object obj = mozillaJsContext.evaluateString(scope, script, "TestScript", 1, null);
        return (long) Context.toNumber(obj);
    } finally {
        Context.exit();
    }
}

Sample:

System.out.println(parseDateUsingRhino("2015-10-25T15:06:42.000Z")); // prints 1445785602000

Side note: this was tested with Rhino 1.7.7.

You should try it first like this and see if it works:

private static long parseDateUsingRhino(String dateInUnknownFormat){
        Context mozillaJsContext = Context.enter();
        Scriptable scope = mozillaJsContext.initStandardObjects();
        String script = "var date = new Date().getTime();";
        Object result = mozillaJsContext.evaluateString( scope, script, "", 1, null );
        return Long.valueOf(Context.toString(result));
    }

And according to this all you need to do next is pass the dateInUnknownFormat variable like so, no java string concatenation required (the context is smart enough to probably consider the java method's accessible variables as global variables in the javascript scope):

String script = "var date = new Date(dateInUnknownFormat).getTime();";

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!