Java Date not interoperable with JavaScript Date

Enonic version: 6.7.2
OS: Mac

If you have Java code returning a Date object, you will not be able to use this as a Date object in JavaScript.

The problem is that Java Date.toString() returns a format of Fri Sep 09 09:01:00 CEST 2016. However if you try to instantiate a JavaScript object using that information var myDate = new Date('Fri Sep 09 09:01:00 CEST 2016'); you will get Invalid Date.

I made a workaround using

public String getISODate (Date input) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");

    return sdf.format(input);
}

The output from there can be used to instantiate a JavaScript date object.

I understand that its Java’s fault for not outputting a ISO standard date, but it is kinda unintuitive that the Date objects dont work together - so if there is a way to fix it, it would be cool if you did :slight_smile:

1 Like

Just a side note; have you tried this in your controller?

var currentDate = new Date().toISOString();

We use it before querying for content in XP. But it’s JS to Java/ES.

Haven’t tried, but for me its the other way around that poses a problem. Will keep it in mind when creating queries though :wink: