Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse org.mozilla.javascript.NativeDate in Java.util.Date

I'm trying to parse a date that i get from JavaScript script evaluated with rhino library into java.util.Date, can i convert a org.mozilla.javascript.NativeDate into a java.util.Date ?

If convert NativeDate into a string with the Context.tostring method i get a date in the following format :

Wed Oct 12 2011 16:17:59 GMT+0200 (CEST)

How can i parse this string date representation in to a java.util.Date object ?

like image 401
aleroot Avatar asked Oct 12 '11 14:10

aleroot


2 Answers

In Rhino use

context.jsToJava(nativeDateObj, Date.class);

like image 146
bvesco Avatar answered Nov 03 '22 11:11

bvesco


Bvesco's answer works well. However doing this the other way round (java to js) is not entirely as simple - Context.javaTojs() does not work for dates. I eventually found the solution here - use the javascript constructor:

Object js = context.newObject(scope, "Date", new Object[] {date.getTime()});

The above post also mentioned the following alternative to convert a date from js to java (I haven't confirmed this):

Date date = new Date((long) ScriptRuntime.toNumber(s)); 
like image 5
Ralf Avatar answered Nov 03 '22 13:11

Ralf