Wrong date format when submit Spring form










5















I have a project where I use Spring MVC and Thymeleaf.
I need to display dates with a different format for each user based on his preferences.
For exemple, UserA want to display dates like MM/dd/yyyy and UserB want to display dates like dd/MM/yyyy.



To do this, I use this thymeleaf parameter:



th:value="$#dates.format(myDate, dateFormat)"


The value "dateFormat" is based on the user preference. This works fine.



My problem is that the date input is in a form, and when I submit the form, it doesn't take the good format. I always get MM/dd/yyyy.



If I choose the format dd/MM/yyyy and enter 18/01/2016, in my spring controller I obtain "Thu Jun 01 00:00:00 CEST 2017" which correspond to 01/06/2017 in dd/MM/yyyy.



What can I do to have the date with the format that I want?



Here is my code:



<form th:action="@/test" th:object="$filter" th:method="POST">
<input type="date" th:type="date" class="form-control" th:id="myDate"
th:name="myDate" th:value="$#dates.format(filter.myDate, dateFormat)"/>
</form>


Controller:



@RequestMapping(value = "/test", method = RequestMethod.POST)
public String myTest(@ModelAttribute Filter filter, Model model)

Systeme.out.println(model.dateFormat);
// dd/MM/yyyy

Systeme.out.println(filter.myDate.toString());
// Thu Jun 01 00:00:00 CEST 2017

return "test";










share|improve this question
























  • Any reference?....

    – deFreitas
    Dec 18 '16 at 4:05















5















I have a project where I use Spring MVC and Thymeleaf.
I need to display dates with a different format for each user based on his preferences.
For exemple, UserA want to display dates like MM/dd/yyyy and UserB want to display dates like dd/MM/yyyy.



To do this, I use this thymeleaf parameter:



th:value="$#dates.format(myDate, dateFormat)"


The value "dateFormat" is based on the user preference. This works fine.



My problem is that the date input is in a form, and when I submit the form, it doesn't take the good format. I always get MM/dd/yyyy.



If I choose the format dd/MM/yyyy and enter 18/01/2016, in my spring controller I obtain "Thu Jun 01 00:00:00 CEST 2017" which correspond to 01/06/2017 in dd/MM/yyyy.



What can I do to have the date with the format that I want?



Here is my code:



<form th:action="@/test" th:object="$filter" th:method="POST">
<input type="date" th:type="date" class="form-control" th:id="myDate"
th:name="myDate" th:value="$#dates.format(filter.myDate, dateFormat)"/>
</form>


Controller:



@RequestMapping(value = "/test", method = RequestMethod.POST)
public String myTest(@ModelAttribute Filter filter, Model model)

Systeme.out.println(model.dateFormat);
// dd/MM/yyyy

Systeme.out.println(filter.myDate.toString());
// Thu Jun 01 00:00:00 CEST 2017

return "test";










share|improve this question
























  • Any reference?....

    – deFreitas
    Dec 18 '16 at 4:05













5












5








5


1






I have a project where I use Spring MVC and Thymeleaf.
I need to display dates with a different format for each user based on his preferences.
For exemple, UserA want to display dates like MM/dd/yyyy and UserB want to display dates like dd/MM/yyyy.



To do this, I use this thymeleaf parameter:



th:value="$#dates.format(myDate, dateFormat)"


The value "dateFormat" is based on the user preference. This works fine.



My problem is that the date input is in a form, and when I submit the form, it doesn't take the good format. I always get MM/dd/yyyy.



If I choose the format dd/MM/yyyy and enter 18/01/2016, in my spring controller I obtain "Thu Jun 01 00:00:00 CEST 2017" which correspond to 01/06/2017 in dd/MM/yyyy.



What can I do to have the date with the format that I want?



Here is my code:



<form th:action="@/test" th:object="$filter" th:method="POST">
<input type="date" th:type="date" class="form-control" th:id="myDate"
th:name="myDate" th:value="$#dates.format(filter.myDate, dateFormat)"/>
</form>


Controller:



@RequestMapping(value = "/test", method = RequestMethod.POST)
public String myTest(@ModelAttribute Filter filter, Model model)

Systeme.out.println(model.dateFormat);
// dd/MM/yyyy

Systeme.out.println(filter.myDate.toString());
// Thu Jun 01 00:00:00 CEST 2017

return "test";










share|improve this question
















I have a project where I use Spring MVC and Thymeleaf.
I need to display dates with a different format for each user based on his preferences.
For exemple, UserA want to display dates like MM/dd/yyyy and UserB want to display dates like dd/MM/yyyy.



To do this, I use this thymeleaf parameter:



th:value="$#dates.format(myDate, dateFormat)"


The value "dateFormat" is based on the user preference. This works fine.



My problem is that the date input is in a form, and when I submit the form, it doesn't take the good format. I always get MM/dd/yyyy.



If I choose the format dd/MM/yyyy and enter 18/01/2016, in my spring controller I obtain "Thu Jun 01 00:00:00 CEST 2017" which correspond to 01/06/2017 in dd/MM/yyyy.



What can I do to have the date with the format that I want?



Here is my code:



<form th:action="@/test" th:object="$filter" th:method="POST">
<input type="date" th:type="date" class="form-control" th:id="myDate"
th:name="myDate" th:value="$#dates.format(filter.myDate, dateFormat)"/>
</form>


Controller:



@RequestMapping(value = "/test", method = RequestMethod.POST)
public String myTest(@ModelAttribute Filter filter, Model model)

Systeme.out.println(model.dateFormat);
// dd/MM/yyyy

Systeme.out.println(filter.myDate.toString());
// Thu Jun 01 00:00:00 CEST 2017

return "test";







forms date spring-mvc formatting thymeleaf






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jul 23 '18 at 15:14









Mahozad

1,70251132




1,70251132










asked Jan 18 '16 at 15:59









YLombardiYLombardi

9211331




9211331












  • Any reference?....

    – deFreitas
    Dec 18 '16 at 4:05

















  • Any reference?....

    – deFreitas
    Dec 18 '16 at 4:05
















Any reference?....

– deFreitas
Dec 18 '16 at 4:05





Any reference?....

– deFreitas
Dec 18 '16 at 4:05












3 Answers
3






active

oldest

votes


















6














After a day of research, I found that Spring read the value that is sent in the web request and try to bind it with the Filter object.



For a date value, it excepts to find a value with the "MM/dd/yyyy" format. If you send a value with another format, it doesn't work.



To solve this problem, you can use the annotation "InitBinder".



@InitBinder
private void dateBinder(WebDataBinder binder)
//The date format to parse or output your dates
SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormat());
//Create a new CustomDateEditor
CustomDateEditor editor = new CustomDateEditor(dateFormat, true);
//Register it as custom editor for the Date type
binder.registerCustomEditor(Date.class, editor);



This method is executed for each web request. Here I call my "dateFormat()" method to get the format in the user preference and say to Spring that all the java.util.Date that it find in web requests have this format.



Here is my full code :



Filter :



import java.util.Date;

@lombok.Data
public class TestDateFilter
private Date myDate;

public TestDateFilter()
this.myDate = new Date();




Controller :



@RequestMapping(value = "/testdate")
public String testDate(Model model)
model.addAttribute("filter", new TestDateFilter());
return "testdate";


@RequestMapping(value = "/testdate", method = RequestMethod.POST)
public String testDatePost(@ModelAttribute("filter") TestDateFilter filter, Model model)
System.out.printf(filter.getLoadingStartDate().toString());
System.out.printf(dateFormat());
return "testdate";


@ModelAttribute("dateFormat")
public String dateFormat()
return userPreferenceService.getDateFormat();


@InitBinder
private void dateBinder(WebDataBinder binder)
//The date format to parse or output your dates
SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormat());
//Create a new CustomDateEditor
CustomDateEditor editor = new CustomDateEditor(dateFormat, true);
//Register it as custom editor for the Date type
binder.registerCustomEditor(Date.class, editor);



HTML :



 <form th:action="@/testdate" th:object="$filter" th:method="POST">
<div class="row">
<div class="col-xs-12 col-sm-6">
<div class="input-group date">
<input type="date" th:type="date" class="form-control"
th:id="loadingStartDate" th:name="loadingStartDate"
th:value="$#dates.format(filter.loadingStartDate, dateFormat)" />
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-xs-12 col-sm-12">
<button type="submit" class="btn btn-primary btn-lg pull-right">
submit
</button>
</div>
</div>
</div>
</form>





share|improve this answer























  • I like this solution, because it allows me to set different formats for different locales

    – Ismael Sarmento
    Nov 28 '17 at 3:36











  • I ran into a problem which led me to this question. I'm going to use your example to illustrate the problem. In testDatePost(), if I were to set @ModelAttribute("filter") TestDateFilter filter on the model before returning (in case of errors), the date format goes back to the default Date.toString() value. For example, my @InitBinder value produced 2018-05-15 19:04:03.0 but when I pass back from the POST it passes as Tue May 15 19:04:03 PDT 2018 which is what this answer fixed in the original case of just loading the form. This only half fixed my issue.

    – wsams
    May 15 '18 at 19:25


















3














You can annotate the Date attribute



 @DateTimeFormat(pattern = "dd/MM/yyyy")
private Date dob;


without Joda dependency since Spring 3.2






share|improve this answer























  • The @DateTimeFormat annotation worked for me inside the Bean. This is the simplest answer and really work!

    – mizerablebr
    Aug 30 '16 at 21:44


















1














I think there are trouble because Spring don't understand that inputted value is a Date.
Is your variable myDate of type java.util.Date?



If it is, try to register a formatter like that :



package your.pack.formatter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.format.Formatter;

public class DateFormatter implements Formatter<Date>

final String defaultDateFormat = "dd.MM.yyyy";

@Override
public String print(Date object, Locale locale)
return new SimpleDateFormat(defaultDateFormat).format(object);


@Override
public Date parse(String text, Locale locale) throws ParseException
return DateUtils.parseDate(text, defaultDateFormat);




Then register it in your configuration :



@Configuration
public class ConversionServiceConfig extends WebMvcConfigurerAdapter

@Bean
public DateFormatter dateFormatter()
return new DateFormatter();


@Override
public void addFormatters(FormatterRegistry registry)
registry.addFormatter(dateFormatter());




But I don't know how to make it works dynamically as you want...



Are users preferences store in database or in properties?






share|improve this answer























  • My variable is a java.util.Date and I store the preferences in a database. In my controller, I have a method with "RequestMapping" that call a service to get the preference. I finally found a solution by using "InitBinder" annotation.

    – YLombardi
    Jan 19 '16 at 14:14










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f34858989%2fwrong-date-format-when-submit-spring-form%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























3 Answers
3






active

oldest

votes








3 Answers
3






active

oldest

votes









active

oldest

votes






active

oldest

votes









6














After a day of research, I found that Spring read the value that is sent in the web request and try to bind it with the Filter object.



For a date value, it excepts to find a value with the "MM/dd/yyyy" format. If you send a value with another format, it doesn't work.



To solve this problem, you can use the annotation "InitBinder".



@InitBinder
private void dateBinder(WebDataBinder binder)
//The date format to parse or output your dates
SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormat());
//Create a new CustomDateEditor
CustomDateEditor editor = new CustomDateEditor(dateFormat, true);
//Register it as custom editor for the Date type
binder.registerCustomEditor(Date.class, editor);



This method is executed for each web request. Here I call my "dateFormat()" method to get the format in the user preference and say to Spring that all the java.util.Date that it find in web requests have this format.



Here is my full code :



Filter :



import java.util.Date;

@lombok.Data
public class TestDateFilter
private Date myDate;

public TestDateFilter()
this.myDate = new Date();




Controller :



@RequestMapping(value = "/testdate")
public String testDate(Model model)
model.addAttribute("filter", new TestDateFilter());
return "testdate";


@RequestMapping(value = "/testdate", method = RequestMethod.POST)
public String testDatePost(@ModelAttribute("filter") TestDateFilter filter, Model model)
System.out.printf(filter.getLoadingStartDate().toString());
System.out.printf(dateFormat());
return "testdate";


@ModelAttribute("dateFormat")
public String dateFormat()
return userPreferenceService.getDateFormat();


@InitBinder
private void dateBinder(WebDataBinder binder)
//The date format to parse or output your dates
SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormat());
//Create a new CustomDateEditor
CustomDateEditor editor = new CustomDateEditor(dateFormat, true);
//Register it as custom editor for the Date type
binder.registerCustomEditor(Date.class, editor);



HTML :



 <form th:action="@/testdate" th:object="$filter" th:method="POST">
<div class="row">
<div class="col-xs-12 col-sm-6">
<div class="input-group date">
<input type="date" th:type="date" class="form-control"
th:id="loadingStartDate" th:name="loadingStartDate"
th:value="$#dates.format(filter.loadingStartDate, dateFormat)" />
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-xs-12 col-sm-12">
<button type="submit" class="btn btn-primary btn-lg pull-right">
submit
</button>
</div>
</div>
</div>
</form>





share|improve this answer























  • I like this solution, because it allows me to set different formats for different locales

    – Ismael Sarmento
    Nov 28 '17 at 3:36











  • I ran into a problem which led me to this question. I'm going to use your example to illustrate the problem. In testDatePost(), if I were to set @ModelAttribute("filter") TestDateFilter filter on the model before returning (in case of errors), the date format goes back to the default Date.toString() value. For example, my @InitBinder value produced 2018-05-15 19:04:03.0 but when I pass back from the POST it passes as Tue May 15 19:04:03 PDT 2018 which is what this answer fixed in the original case of just loading the form. This only half fixed my issue.

    – wsams
    May 15 '18 at 19:25















6














After a day of research, I found that Spring read the value that is sent in the web request and try to bind it with the Filter object.



For a date value, it excepts to find a value with the "MM/dd/yyyy" format. If you send a value with another format, it doesn't work.



To solve this problem, you can use the annotation "InitBinder".



@InitBinder
private void dateBinder(WebDataBinder binder)
//The date format to parse or output your dates
SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormat());
//Create a new CustomDateEditor
CustomDateEditor editor = new CustomDateEditor(dateFormat, true);
//Register it as custom editor for the Date type
binder.registerCustomEditor(Date.class, editor);



This method is executed for each web request. Here I call my "dateFormat()" method to get the format in the user preference and say to Spring that all the java.util.Date that it find in web requests have this format.



Here is my full code :



Filter :



import java.util.Date;

@lombok.Data
public class TestDateFilter
private Date myDate;

public TestDateFilter()
this.myDate = new Date();




Controller :



@RequestMapping(value = "/testdate")
public String testDate(Model model)
model.addAttribute("filter", new TestDateFilter());
return "testdate";


@RequestMapping(value = "/testdate", method = RequestMethod.POST)
public String testDatePost(@ModelAttribute("filter") TestDateFilter filter, Model model)
System.out.printf(filter.getLoadingStartDate().toString());
System.out.printf(dateFormat());
return "testdate";


@ModelAttribute("dateFormat")
public String dateFormat()
return userPreferenceService.getDateFormat();


@InitBinder
private void dateBinder(WebDataBinder binder)
//The date format to parse or output your dates
SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormat());
//Create a new CustomDateEditor
CustomDateEditor editor = new CustomDateEditor(dateFormat, true);
//Register it as custom editor for the Date type
binder.registerCustomEditor(Date.class, editor);



HTML :



 <form th:action="@/testdate" th:object="$filter" th:method="POST">
<div class="row">
<div class="col-xs-12 col-sm-6">
<div class="input-group date">
<input type="date" th:type="date" class="form-control"
th:id="loadingStartDate" th:name="loadingStartDate"
th:value="$#dates.format(filter.loadingStartDate, dateFormat)" />
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-xs-12 col-sm-12">
<button type="submit" class="btn btn-primary btn-lg pull-right">
submit
</button>
</div>
</div>
</div>
</form>





share|improve this answer























  • I like this solution, because it allows me to set different formats for different locales

    – Ismael Sarmento
    Nov 28 '17 at 3:36











  • I ran into a problem which led me to this question. I'm going to use your example to illustrate the problem. In testDatePost(), if I were to set @ModelAttribute("filter") TestDateFilter filter on the model before returning (in case of errors), the date format goes back to the default Date.toString() value. For example, my @InitBinder value produced 2018-05-15 19:04:03.0 but when I pass back from the POST it passes as Tue May 15 19:04:03 PDT 2018 which is what this answer fixed in the original case of just loading the form. This only half fixed my issue.

    – wsams
    May 15 '18 at 19:25













6












6








6







After a day of research, I found that Spring read the value that is sent in the web request and try to bind it with the Filter object.



For a date value, it excepts to find a value with the "MM/dd/yyyy" format. If you send a value with another format, it doesn't work.



To solve this problem, you can use the annotation "InitBinder".



@InitBinder
private void dateBinder(WebDataBinder binder)
//The date format to parse or output your dates
SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormat());
//Create a new CustomDateEditor
CustomDateEditor editor = new CustomDateEditor(dateFormat, true);
//Register it as custom editor for the Date type
binder.registerCustomEditor(Date.class, editor);



This method is executed for each web request. Here I call my "dateFormat()" method to get the format in the user preference and say to Spring that all the java.util.Date that it find in web requests have this format.



Here is my full code :



Filter :



import java.util.Date;

@lombok.Data
public class TestDateFilter
private Date myDate;

public TestDateFilter()
this.myDate = new Date();




Controller :



@RequestMapping(value = "/testdate")
public String testDate(Model model)
model.addAttribute("filter", new TestDateFilter());
return "testdate";


@RequestMapping(value = "/testdate", method = RequestMethod.POST)
public String testDatePost(@ModelAttribute("filter") TestDateFilter filter, Model model)
System.out.printf(filter.getLoadingStartDate().toString());
System.out.printf(dateFormat());
return "testdate";


@ModelAttribute("dateFormat")
public String dateFormat()
return userPreferenceService.getDateFormat();


@InitBinder
private void dateBinder(WebDataBinder binder)
//The date format to parse or output your dates
SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormat());
//Create a new CustomDateEditor
CustomDateEditor editor = new CustomDateEditor(dateFormat, true);
//Register it as custom editor for the Date type
binder.registerCustomEditor(Date.class, editor);



HTML :



 <form th:action="@/testdate" th:object="$filter" th:method="POST">
<div class="row">
<div class="col-xs-12 col-sm-6">
<div class="input-group date">
<input type="date" th:type="date" class="form-control"
th:id="loadingStartDate" th:name="loadingStartDate"
th:value="$#dates.format(filter.loadingStartDate, dateFormat)" />
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-xs-12 col-sm-12">
<button type="submit" class="btn btn-primary btn-lg pull-right">
submit
</button>
</div>
</div>
</div>
</form>





share|improve this answer













After a day of research, I found that Spring read the value that is sent in the web request and try to bind it with the Filter object.



For a date value, it excepts to find a value with the "MM/dd/yyyy" format. If you send a value with another format, it doesn't work.



To solve this problem, you can use the annotation "InitBinder".



@InitBinder
private void dateBinder(WebDataBinder binder)
//The date format to parse or output your dates
SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormat());
//Create a new CustomDateEditor
CustomDateEditor editor = new CustomDateEditor(dateFormat, true);
//Register it as custom editor for the Date type
binder.registerCustomEditor(Date.class, editor);



This method is executed for each web request. Here I call my "dateFormat()" method to get the format in the user preference and say to Spring that all the java.util.Date that it find in web requests have this format.



Here is my full code :



Filter :



import java.util.Date;

@lombok.Data
public class TestDateFilter
private Date myDate;

public TestDateFilter()
this.myDate = new Date();




Controller :



@RequestMapping(value = "/testdate")
public String testDate(Model model)
model.addAttribute("filter", new TestDateFilter());
return "testdate";


@RequestMapping(value = "/testdate", method = RequestMethod.POST)
public String testDatePost(@ModelAttribute("filter") TestDateFilter filter, Model model)
System.out.printf(filter.getLoadingStartDate().toString());
System.out.printf(dateFormat());
return "testdate";


@ModelAttribute("dateFormat")
public String dateFormat()
return userPreferenceService.getDateFormat();


@InitBinder
private void dateBinder(WebDataBinder binder)
//The date format to parse or output your dates
SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormat());
//Create a new CustomDateEditor
CustomDateEditor editor = new CustomDateEditor(dateFormat, true);
//Register it as custom editor for the Date type
binder.registerCustomEditor(Date.class, editor);



HTML :



 <form th:action="@/testdate" th:object="$filter" th:method="POST">
<div class="row">
<div class="col-xs-12 col-sm-6">
<div class="input-group date">
<input type="date" th:type="date" class="form-control"
th:id="loadingStartDate" th:name="loadingStartDate"
th:value="$#dates.format(filter.loadingStartDate, dateFormat)" />
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-xs-12 col-sm-12">
<button type="submit" class="btn btn-primary btn-lg pull-right">
submit
</button>
</div>
</div>
</div>
</form>






share|improve this answer












share|improve this answer



share|improve this answer










answered Jan 19 '16 at 14:23









YLombardiYLombardi

9211331




9211331












  • I like this solution, because it allows me to set different formats for different locales

    – Ismael Sarmento
    Nov 28 '17 at 3:36











  • I ran into a problem which led me to this question. I'm going to use your example to illustrate the problem. In testDatePost(), if I were to set @ModelAttribute("filter") TestDateFilter filter on the model before returning (in case of errors), the date format goes back to the default Date.toString() value. For example, my @InitBinder value produced 2018-05-15 19:04:03.0 but when I pass back from the POST it passes as Tue May 15 19:04:03 PDT 2018 which is what this answer fixed in the original case of just loading the form. This only half fixed my issue.

    – wsams
    May 15 '18 at 19:25

















  • I like this solution, because it allows me to set different formats for different locales

    – Ismael Sarmento
    Nov 28 '17 at 3:36











  • I ran into a problem which led me to this question. I'm going to use your example to illustrate the problem. In testDatePost(), if I were to set @ModelAttribute("filter") TestDateFilter filter on the model before returning (in case of errors), the date format goes back to the default Date.toString() value. For example, my @InitBinder value produced 2018-05-15 19:04:03.0 but when I pass back from the POST it passes as Tue May 15 19:04:03 PDT 2018 which is what this answer fixed in the original case of just loading the form. This only half fixed my issue.

    – wsams
    May 15 '18 at 19:25
















I like this solution, because it allows me to set different formats for different locales

– Ismael Sarmento
Nov 28 '17 at 3:36





I like this solution, because it allows me to set different formats for different locales

– Ismael Sarmento
Nov 28 '17 at 3:36













I ran into a problem which led me to this question. I'm going to use your example to illustrate the problem. In testDatePost(), if I were to set @ModelAttribute("filter") TestDateFilter filter on the model before returning (in case of errors), the date format goes back to the default Date.toString() value. For example, my @InitBinder value produced 2018-05-15 19:04:03.0 but when I pass back from the POST it passes as Tue May 15 19:04:03 PDT 2018 which is what this answer fixed in the original case of just loading the form. This only half fixed my issue.

– wsams
May 15 '18 at 19:25





I ran into a problem which led me to this question. I'm going to use your example to illustrate the problem. In testDatePost(), if I were to set @ModelAttribute("filter") TestDateFilter filter on the model before returning (in case of errors), the date format goes back to the default Date.toString() value. For example, my @InitBinder value produced 2018-05-15 19:04:03.0 but when I pass back from the POST it passes as Tue May 15 19:04:03 PDT 2018 which is what this answer fixed in the original case of just loading the form. This only half fixed my issue.

– wsams
May 15 '18 at 19:25













3














You can annotate the Date attribute



 @DateTimeFormat(pattern = "dd/MM/yyyy")
private Date dob;


without Joda dependency since Spring 3.2






share|improve this answer























  • The @DateTimeFormat annotation worked for me inside the Bean. This is the simplest answer and really work!

    – mizerablebr
    Aug 30 '16 at 21:44















3














You can annotate the Date attribute



 @DateTimeFormat(pattern = "dd/MM/yyyy")
private Date dob;


without Joda dependency since Spring 3.2






share|improve this answer























  • The @DateTimeFormat annotation worked for me inside the Bean. This is the simplest answer and really work!

    – mizerablebr
    Aug 30 '16 at 21:44













3












3








3







You can annotate the Date attribute



 @DateTimeFormat(pattern = "dd/MM/yyyy")
private Date dob;


without Joda dependency since Spring 3.2






share|improve this answer













You can annotate the Date attribute



 @DateTimeFormat(pattern = "dd/MM/yyyy")
private Date dob;


without Joda dependency since Spring 3.2







share|improve this answer












share|improve this answer



share|improve this answer










answered May 22 '16 at 12:46









Pierpaolo PagnoniPierpaolo Pagnoni

4113




4113












  • The @DateTimeFormat annotation worked for me inside the Bean. This is the simplest answer and really work!

    – mizerablebr
    Aug 30 '16 at 21:44

















  • The @DateTimeFormat annotation worked for me inside the Bean. This is the simplest answer and really work!

    – mizerablebr
    Aug 30 '16 at 21:44
















The @DateTimeFormat annotation worked for me inside the Bean. This is the simplest answer and really work!

– mizerablebr
Aug 30 '16 at 21:44





The @DateTimeFormat annotation worked for me inside the Bean. This is the simplest answer and really work!

– mizerablebr
Aug 30 '16 at 21:44











1














I think there are trouble because Spring don't understand that inputted value is a Date.
Is your variable myDate of type java.util.Date?



If it is, try to register a formatter like that :



package your.pack.formatter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.format.Formatter;

public class DateFormatter implements Formatter<Date>

final String defaultDateFormat = "dd.MM.yyyy";

@Override
public String print(Date object, Locale locale)
return new SimpleDateFormat(defaultDateFormat).format(object);


@Override
public Date parse(String text, Locale locale) throws ParseException
return DateUtils.parseDate(text, defaultDateFormat);




Then register it in your configuration :



@Configuration
public class ConversionServiceConfig extends WebMvcConfigurerAdapter

@Bean
public DateFormatter dateFormatter()
return new DateFormatter();


@Override
public void addFormatters(FormatterRegistry registry)
registry.addFormatter(dateFormatter());




But I don't know how to make it works dynamically as you want...



Are users preferences store in database or in properties?






share|improve this answer























  • My variable is a java.util.Date and I store the preferences in a database. In my controller, I have a method with "RequestMapping" that call a service to get the preference. I finally found a solution by using "InitBinder" annotation.

    – YLombardi
    Jan 19 '16 at 14:14















1














I think there are trouble because Spring don't understand that inputted value is a Date.
Is your variable myDate of type java.util.Date?



If it is, try to register a formatter like that :



package your.pack.formatter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.format.Formatter;

public class DateFormatter implements Formatter<Date>

final String defaultDateFormat = "dd.MM.yyyy";

@Override
public String print(Date object, Locale locale)
return new SimpleDateFormat(defaultDateFormat).format(object);


@Override
public Date parse(String text, Locale locale) throws ParseException
return DateUtils.parseDate(text, defaultDateFormat);




Then register it in your configuration :



@Configuration
public class ConversionServiceConfig extends WebMvcConfigurerAdapter

@Bean
public DateFormatter dateFormatter()
return new DateFormatter();


@Override
public void addFormatters(FormatterRegistry registry)
registry.addFormatter(dateFormatter());




But I don't know how to make it works dynamically as you want...



Are users preferences store in database or in properties?






share|improve this answer























  • My variable is a java.util.Date and I store the preferences in a database. In my controller, I have a method with "RequestMapping" that call a service to get the preference. I finally found a solution by using "InitBinder" annotation.

    – YLombardi
    Jan 19 '16 at 14:14













1












1








1







I think there are trouble because Spring don't understand that inputted value is a Date.
Is your variable myDate of type java.util.Date?



If it is, try to register a formatter like that :



package your.pack.formatter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.format.Formatter;

public class DateFormatter implements Formatter<Date>

final String defaultDateFormat = "dd.MM.yyyy";

@Override
public String print(Date object, Locale locale)
return new SimpleDateFormat(defaultDateFormat).format(object);


@Override
public Date parse(String text, Locale locale) throws ParseException
return DateUtils.parseDate(text, defaultDateFormat);




Then register it in your configuration :



@Configuration
public class ConversionServiceConfig extends WebMvcConfigurerAdapter

@Bean
public DateFormatter dateFormatter()
return new DateFormatter();


@Override
public void addFormatters(FormatterRegistry registry)
registry.addFormatter(dateFormatter());




But I don't know how to make it works dynamically as you want...



Are users preferences store in database or in properties?






share|improve this answer













I think there are trouble because Spring don't understand that inputted value is a Date.
Is your variable myDate of type java.util.Date?



If it is, try to register a formatter like that :



package your.pack.formatter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.format.Formatter;

public class DateFormatter implements Formatter<Date>

final String defaultDateFormat = "dd.MM.yyyy";

@Override
public String print(Date object, Locale locale)
return new SimpleDateFormat(defaultDateFormat).format(object);


@Override
public Date parse(String text, Locale locale) throws ParseException
return DateUtils.parseDate(text, defaultDateFormat);




Then register it in your configuration :



@Configuration
public class ConversionServiceConfig extends WebMvcConfigurerAdapter

@Bean
public DateFormatter dateFormatter()
return new DateFormatter();


@Override
public void addFormatters(FormatterRegistry registry)
registry.addFormatter(dateFormatter());




But I don't know how to make it works dynamically as you want...



Are users preferences store in database or in properties?







share|improve this answer












share|improve this answer



share|improve this answer










answered Jan 19 '16 at 8:39









sanlucksanluck

1,2411819




1,2411819












  • My variable is a java.util.Date and I store the preferences in a database. In my controller, I have a method with "RequestMapping" that call a service to get the preference. I finally found a solution by using "InitBinder" annotation.

    – YLombardi
    Jan 19 '16 at 14:14

















  • My variable is a java.util.Date and I store the preferences in a database. In my controller, I have a method with "RequestMapping" that call a service to get the preference. I finally found a solution by using "InitBinder" annotation.

    – YLombardi
    Jan 19 '16 at 14:14
















My variable is a java.util.Date and I store the preferences in a database. In my controller, I have a method with "RequestMapping" that call a service to get the preference. I finally found a solution by using "InitBinder" annotation.

– YLombardi
Jan 19 '16 at 14:14





My variable is a java.util.Date and I store the preferences in a database. In my controller, I have a method with "RequestMapping" that call a service to get the preference. I finally found a solution by using "InitBinder" annotation.

– YLombardi
Jan 19 '16 at 14:14

















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f34858989%2fwrong-date-format-when-submit-spring-form%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

How to how show current date and time by default on contact form 7 in WordPress without taking input from user in datetimepicker

Syphilis

Darth Vader #20