Last active
May 20, 2020 11:01
-
-
Save UnquietCode/5614860 to your computer and use it in GitHub Desktop.
Code for running moment.js under Java using the Rhino script engine. https://github.com/timrwood/moment/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static final String MOMENT_JS_FILE = "moment.min.js"; | |
private static JSInvocable newMoment(Long epoch) { | |
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(MOMENT_JS_FILE); | |
Reader reader = new InputStreamReader(is); | |
ScriptEngineManager manager = new ScriptEngineManager(); | |
ScriptEngine engine = manager.getEngineByName("JavaScript"); | |
Object moment; | |
try { | |
engine.eval(reader); | |
if (epoch == null) { | |
moment = ((Invocable) engine).invokeFunction("moment"); | |
} else { | |
moment = ((Invocable) engine).invokeFunction("moment", epoch); | |
} | |
} catch (Exception ex) { | |
throw new RuntimeException(ex); | |
} | |
return new JSInvocable((Invocable) engine, moment); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class JSInvocable { | |
private final Invocable invocable; | |
private final Object object; | |
private JSInvocable(Invocable invocable, Object object) { | |
this.invocable = invocable; | |
this.object = object; | |
} | |
public String invoke(String method, Object...args) { | |
if (args == null) { args = new Object[0]; } | |
try { | |
return invocable.invokeMethod(object, method, args).toString(); | |
} catch (Exception ex) { | |
throw new RuntimeException(ex); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I’m a nubi at this and I am trying to calculate the difference between 2 date values, (ISO8601 format - this is the format that I am getting it in)
var d1 = new Date('2015-07-12T15:06:23');
var d2 = new Date('2015-07-14T16:09:33');
var diff = d2.getTime() - d1.getTime();
return diff;
I am getting NaN.
When I run this;
var d1 = new Date('2015-07-12T15:06:23');
return d1;
I get something like this;
org.mozilla.javascript.NativeDate@2bcf1082
Any help would be greatly appreciated.
Thanx.