Javascript – Java date format to JavaScript date format

date-format, java, javascript

I would like to be able to convert a Java date format string, e.g. dd/MM/yyyy (07/06/2009) to a JavaScript date format string, e.g. dd/mm/yy (07/06/2009).

Has anyone done this before, or got any idea where I might find some code that already does this?

Thanks in advance.


Thanks for all the replies but now I realize my mistake and possibly why so many of you were struggling to understand the question; JavaScript doesn't have a built in date formatting ability. I am using the jQuery UI datepicker and I have been setting its date format, assuming it would be calling a standard JS function at some point, not using its own library! When I googled for formatting strings I jumped straight to the tables of what letters could be used, skipping the bit at the beginning explaining how to use the script.

Anyway I'll have to go ahead and possibly write my own I guess, converting a Java date format string into a jQuery date format string (or as close as possible) – I am working on the i18n of our product and have created a java class that stores the preferred date format string used throughout the application, my intention was to also have the ability to supply any jsps with the format string that is equivalent in JS.

Thanks anyway.

Best Solution

If you just need to pass a date from Java to JavaScript, the best way to do it, I think, would be to convert the Java date to milliseconds using date.getTime(), create a JavaScript date initialized with this milliseconds value with new Date(milliseconds)and then format the date with the means of the JavaScript Date object, like: date.toLocaleString().