java rhino 运行 js,使用Rhino而不是ScriptEngine在Java中运行Javascript代码

Based on the discussion converting string representation of unknown date-format to Date in java, I want to use the JavaScript Date function in my App-Engine project. However, ScriptEngine does not work on App-Engine. So I need a little help converting to Rhino. Here is the ScriptEngine code I need to convert:

ScriptEngineManager scriptEngineManager = new ScriptEngineManager();

ScriptEngine engine = scriptEngineManager.getEngineByName("JavaScript");

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

engine.eval(script);

long timestamp = ((Double) engine.get("timestamp")).longValue();

The following has not worked

private static long parseDateUsingRhino(String dateInUnknownFormat){

Context mozillaJsContext = Context.enter();

Scriptable scope = mozillaJsContext.initStandardObjects();

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

Object obj = mozillaJsContext.evaluateString( scope, script, "TestScript", 1, null );

Double timeDouble = Double.parseDouble((String) obj);

long timestamp = timeDouble.longValue();

return timestamp;

}

and I have already replaced "TestScript" with null and "".

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值