Skip to content

Instantly share code, notes, and snippets.

@UnquietCode
Last active May 20, 2020 11:01
Show Gist options
  • Save UnquietCode/5614860 to your computer and use it in GitHub Desktop.
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/
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);
}
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);
}
}
}
@dwygonow
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment