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 ?

3 Answers 3

8

In Rhino use

context.jsToJava(nativeDateObj, Date.class);

Sign up to request clarification or add additional context in comments.

1 Comment

In case anyone wondered, that is a static method, you don't need access to the script context.
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)); 

2 Comments

Using the javascript constructor works when going to JS. Thanks!
Might you help me with my problem. I am trying to apply your solution but I don't know how: stackoverflow.com/questions/33192485/…
-2

Have you tried;?

java.sql.Date.valueOf("date string");

5 Comments

The method valueOf(String) is undefined for the type Date
Undefined? The method exists in SE Java: download.oracle.com/javase/6/docs/api/java/sql/…
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 ?
it should be obvious that you will need to parse the string somewhat

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.