Subj : Re: best way to create native javascript date from Java with Rhino To : Barnabas Wolf From : Igor Bukanov Date : Mon Feb 03 2003 03:58 pm Barnabas Wolf wrote: > What is the best way to create a JavaScript Date object from Java? > Rhino wraps java.util.Date's using NativeJavaObject; it does not > convert them to NativeDate. I am currently using a workaround in a > WrapFactory: > > if (val instanceof java.util.Date) { > long time=((java.util.Date) val).getTime(); > return cx.evaluateString( > scope, "new Date(" + time + ");", > "date conversion", 1, null) > } > > Is there a better way to do this? (More efficient or more elegant > way?) > To call a constructor defined in the given scope, use Context.toObject(), http://mozilla.org/rhino/apidocs/org/mozilla/javascript/Context.html#newObject(org.mozilla.javascript.Scriptable,%20java.lang.String,%20java.lang.Object[]) So in your case you will have: if (val instanceof java.util.Date) { long time=((java.util.Date) val).getTime(); return cx.newObject(scope, "Date", new Object[] { new Double(time) }); } > Is there a specific reason Rhino is not able to convert Dates into > native types, like it can with Numbers and Strings? > Rhino does not by default converts Java Number and String objects to corresponding primitive types. Instead it wraps them to a special script objects in the same way as it expose any other JavaObject to scripts via LiveConnect, it only converts primitive Java values to corresponding script values. To override this, you need to provide a custom WrapHandler (WrapFactory in the forthcoming Rhino 1.5R4). java.util.Date and Date objects in JavaScript are sufficiently different not only by their API, but also by internal presentation. In particular, Date in Script can hold NaN value while java.util.Date can not. For these reasons it is best to left to applications to decide how to convert one to another. Regards, Igor .