New Date() with UK format

Hi there,

Recently we found something weird with the new Date() function.

Customer supplied data in UK format, DD/MM/YYYY

e.g. “26/02/2022”

the ori JS does not support DD/MM/YYYY so that it should show Invalid Date when you call new Date();

However when you call new Date() in designer which will treat 26 as month and automatically calculate to year.

image

That especially confused people if they use date.getMonth() only

Both 26/02/2022 and 02/26/2022 are showing Month is Feb, so that people may think new Date() is working fine with UK format as well

So any particular reason why new Date() is doing an incorrect conversion automatically when date format is wrong in Designer? Or is there any special way to use new Date() in Designer with UK format?

Thanks

I am not certain why yet but using “26-02-2022” instead of “26/02/2022” does result in “Invalid Date” when applying it the following way in a Standard Script:

Name: Test
Selector: #test

var field, result = "";

field = "26-02-2022"; //"26/02/2022";

if (field !== "") {
    var date = new Date(field);

    result += date.toString();
}

results.html(result);

So a quick workaround might be to use…

var date = new Date(field.replace(/\//g, "-"));

…instead of…

var date = new Date(field);

…to replace forward slash characters with minus characters.


Tested in PReS Connect version 2022.1.4

Thanks for coming back to me, yeah, the date formating is not a issue, we can treat it as string and reformat it easily.

Really appreciate if you can figure out the reason why the same function working is differently, little bit consent if there is anything more different between Js and presConnect Designer Js has not been announced

Thanks

User scripts (i.e. entries in the Scripts panel) are interpreted by Rhino, which is backed by Java.

2022.1 still uses 1.7.12 but this will be updated to 1.7.14 in 2022.2. This will have many benefits but unfortunately it will not change the behavior of “new Date”.

For a more accurate representation of Rhino you should not use jsfiddle (which would be interpreted by whatever browser you happen to use) but something like Online Compiler and Editor/IDE for Java, C, C++, PHP, Python, Ruby, Perl - Code and Run Online with the following expression:

print(new Date("26/02/2022"));

The output should be the same as for user scripts in Connect.

1 Like