varun
varun

Reputation: 726

Implement configurable date format in spring mvc and jquery

I want to give an option to configure date-format for the application in properties file. I had thought of implementing it using conversion service in spring and a model which I will use as date format property for jquery datepicker. As I went a little further I found out that SimpleDateFormat and jquery datepicker formats the date in different pattern for the same format string. There should have been a standard for this but unfortunately that is not the case. What is the other way to do this?

Upvotes: 3

Views: 823

Answers (1)

MattSenter
MattSenter

Reputation: 3120

It took me a few reads to fully grasp what the problem was, but it sounds like you know how to do the formatting with Spring but are having issues with the fact that jquery uses different patterns than Java when formatting a Date? I believe your best recourse may be to simply store two patterns in your properties:

java.date.format=yyyy-MM-dd...
jquery.date.format=yyyy-mm-dd...

Obviously that means configuration would require making sure you used the equivalent format for each property so that they were always converted properly, but the only alternative I can see is creating an automatic format converter from jquery to java (or vice versa.)

Alternatively, have you considered simply converting the date to milliseconds before submitting and then using that to recreate the Date on the java end? Would be much simpler, I imagine.

EDIT AFTER COMMENTS

Sounds like the goal is ultimately to have a single configurable property:

date.format=yyyy-mm-dd...

In order to avoid a complex mapping from jquery's date formatting tokens to Java's date formatting tokens, it might be best to simply create your own custom date format in the form of:

[millis],[timeZoneOffset]

Your properties file should contain the jquery format string so that your Datepicker will render the format you wish the client to see. Then, when a date is picked, you should convert it to your [millis],[timeZoneOffset] custom format before submitting to your controller. On the Spring/Java side, you should create and register a custom Date converter that accepts this [millis],[timeZoneOffset] format and creates the corresponding Date object.

Personally, I don't see anything wrong with creating your own custom date format to solve this problem. You are going to save yourself a lot of headache that would come from trying to map jquery to Java, and, ultimately, it's what Spring's custom converters are there to help with.

Upvotes: 1

Related Questions