Home>

I am currently using spring to create a program.
I asked a question because I was stuck in the process.

To summarize the current situation
The date of birth is specified in the field with the date type of javautil in the form.

I would like to send the date of birth to the form in the format.
Sending the date of birth through HTML in this format will replace the display below.
Sun Oct dd 00:00:00 JST YYYY

using java sql date
I was able to implement it with methods such as YYYY-MM-DD, but

I want to output in the format of yyyy/MM/dd.

Spring.mvc.date-format=yyyy/MM/dd in the application properties
It was not possible to add...

  • Answer # 1

    For example, when the implementation of Controller is as follows,

    import java.util.Date;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.servlet.ModelAndView;
    @Controller
    @RequestMapping("date")
    public class DateController {
        @GetMapping
        public ModelAndView display(ModelAndView mnv) {
            mnv.addObject("nowDate", new Date());
            mnv.setViewName("date");
            return mnv;
        }
    }

    If the screen to be displayed is Thymeleaf HTML template, if noeDate is displayed as is

    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
        
    </body>
    </html>

    Does that mean it will happen like this?

    Tue Jul 14 20:21:41 GMT+09:00 2020

    In that case, specify the date format in the HTML template and it will be solved.

    https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf_ja.html#%E6%97%A5%E4%BB%98

  • Answer # 2

    Does displaying the Date object on the server side in HTML result in an unintended display?
    If it is displayed as it is, it is correct to get such a display.

    If you want to change the format, you should do it on the view side.
    I don't know what you are using for view, but if you have custom tags for date format etc.
    Please go with that.

    If you really want to do it on the server side, set the following values ​​in the Form class.

    String dateString = new SimpleDateFormat("yyyy/MM/dd").format(date);

    In the first place,java.util.DateShould no longer be used, so
    First of alljava.time.LocalDateOrjava.time.LocalDateTimeYou should consider replacing with.
    The format of these classes is as follows.

    LocalDate localDate = LocalDate.now();
    String dateString = localDate.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));