title: Supply JavaScript date to Nashorn script
body: <p>I am working on an API in Java that allows users to write scripts and access a specific set of methods that are passed in (in the form of an API object) by the Nashorn script engine.</p>
  
  <p>I want to, in the JavaScript, call a function getDate(), which will return some arbitrary date (as a native JavaScript date) that's provided from the Java side.</p>
  
  <p>I have tried simply putting an org.java.util.Date on the API object, but that won't behave like a JS date. The goal is to make this as simple as possible for end-users who are experienced with JS.</p>
  
  <p>Java Example:</p>
  
  <pre><code>public class MyAPI {
      public void log(String text){
          System.out.println(text);
      }
  
      public Date getDate(){
          // Return something that converts to a native-JS date
      }
  
      public static void main(){
          // MyClassFilter implements Nashorn's ClassFilter
          ScriptEngine engine = new NashornScriptEngineFactory().getScriptEngine(new MyClassFilter());
          ((Invokable) engine).invokeFunction("entryPoint", new MyAPI());
      }
  </code></pre>
  
  <p>JavaScript example</p>
  
  <pre><code>function entryPoint(myApi){
      var date = myApi.getDate();
      myApi.log(date.getMinutes());
  }
  </code></pre>