5

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 ?

aleroot
  • 71,077
  • 30
  • 176
  • 213

3 Answers3

8

In Rhino use

context.jsToJava(nativeDateObj, Date.class);

bvesco
  • 361
  • 4
  • 8
5

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)); 
Ralf
  • 14,655
  • 9
  • 48
  • 58
-2

Have you tried;?

java.sql.Date.valueOf("date string");
flup
  • 26,937
  • 7
  • 52
  • 74
lynks
  • 5,599
  • 6
  • 23
  • 42
  • The method valueOf(String) is undefined for the type Date – aleroot Oct 12 '11 at 14:51
  • 1
    Undefined? The method exists in SE Java: http://download.oracle.com/javase/6/docs/api/java/sql/Date.html#valueOf(java.lang.String) – lynks Oct 12 '11 at 20:38
  • The method still exists in 7: http://download.oracle.com/javase/7/docs/api/java/sql/Date.html#valueOf(java.lang.String – lynks Oct 12 '11 at 21:15
  • 1
    ok, the method is in the java.sql.Date package, but it doesn't work, if i try to parse that string i get : java.lang.IllegalArgumentException. HAve you tried to parse the string in the post ? – aleroot Oct 12 '11 at 21:15
  • it should be obvious that you will need to parse the string somewhat – lynks Oct 12 '11 at 21:20