How to use @DateTimeFormat to format Date Time request param in SpringBoot RestAPI Examples

springboot-restapi-datetimeformat-feature-image


In the tutorial, we show how to work with DateTime request param in SpringBoot RestAPI using @DateTimeFormat.

@DateTimeFormat with DateTime Request Param

@DateTimeFormat is used to declare a field or method parameter should be formatted as a date or time.

We can use @DateTimeFormat with ISO date time pattern, or custom format pattern string:

– Common ISO enum value: DATE, TIME, DATE_TIME

  • DATE: yyyy-MM-dd, example 2019-03-28
  • TIME: HH:mm:ss.SSSXXX, example 01:30:00.000-05:00
  • DATE_TIME: yyyy-MM-dd'T'HH:mm:ss.SSSXXX, example 2019-03-28T01:30:00.000+07:00

Example @DateTimeFormat with @RequestParam in Spring RestAPI:

– Custom format pattern string:

Example:

Practice

Create SpringBoot project

We create a SpringBoot project as below:

D:\gkz\article\SpringBoot-DateTimeFormat-RestAPI

– Dependency:

Create DateTime RestAPIs

RestAPIs.java:

Run & Check Results

Run SpringBoot project ->
– Request 1 with ISO format pattern:

SpringBoot-RestAPI-DateTimeFormat-project-structure-request-iso-pattern

-> Logs in SpringBoot app:

– Request 2 with Custom format pattern:

SpringBoot-RestAPI-DateTimeFormat-project-structure-request-custom-pattern

-> Logs in SpringBoot app:

Sourcecode

SpringDateTimeFormatExamples

Conclusion

We had learned how to use @DateTimeFormat to format Date Time request param in SpringBoot RestAPI with:

  • ISO date time pattern
  • Custom date time format pattern string

Happy Learning! See you later!

By grokonez | March 28, 2019.



Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*