SoFunction
Updated on 2025-04-11

Several commonly used interface date formatting methods for SpringBoot

Global time formatting

Global time formatting can be achieved by setting it in the configuration file. Add the following two lines of configuration in Spring Boot's configuration file (or):

# Format global time fields-format=yyyy-MM-dd HH:mm:ss
# Specify the time zone type-zone=GMT+8

Implementation principle analysis: When the Controller returns data, it will automatically call Jackson, the built-in JSON framework in Spring Boot framework, and perform unified JSON formatting of the returned data. During the processing process, it will determine whether “-format=yyyy-MM-dd HH:mm:ss” is set in the configuration file. If set, then the Jackson framework will perform time formatting processing when outputting time-type fields, thereby realizing the formatting function of global time fields.

Partial time formatting

In some scenarios, there is no need to uniformly process the global time, and some time fields can be formatted using annotations. Add the @JsonFormat annotation in the entity class UserInfo, and the implementation code is as follows:

import ;
import ;
import ;
 
@Data
public class UserInfo {
    private int id;
    private String username;
    // Format the createtime field    @JsonFormat(pattern = "yyyy-MM-dd hh:mm:ss", timezone = "GMT+8")
    private Date createtime;
    private Date updatetime;
}

Custom parameter converter

In Spring Boot, date formatting can be implemented using a custom parameter converter. Implement interface, custom parameter converter, as follows:

@Configuration
public class DateConverterConfig {
    @Bean
    public Converter<String, LocalDate> localDateConverter() {
        return new Converter<String, LocalDate>() {
            @Override
            public LocalDate convert(String source) {
                return (source, ("yyyy-MM-dd"));
            }
        };
    }
    @Bean
    public Converter<String, LocalDateTime> localDateTimeConverter() {
        return new Converter<String, LocalDateTime>() {
            @Override
            public LocalDateTime convert(String source) {
                return (source, ("yyyy-MM-dd HH:mm:ss"));
            }
        };
    }
}

There may be some problems when using custom parameter converters. For example, when writing anonymous inner classes to lambda expressions, an exception may occur when starting the project. The reason is that the interface of the lambda expression is Converter, and the specific type cannot be obtained. There are two solutions: one is not to use lambda expressions and honestly use anonymous internal classes; the other is to wait until the requestMappingHandlerAdapter bean is registered before adding your own converter, so that you will not register in the FormattingConversionService.

In addition, the string passed by the front end can be regular matched, such as yyyy-MM-dd HH:mm:ss, yyyy-MM-dd, HH:mm:ss, etc., to adapt to various scenarios.

Using Spring Annotations

Spring comes with annotations @DateTimeFormat can be used for date formatting. It is usually used to convert dates in string format to date type. Add annotation on the Date property that needs to be converted to date format @DateTimeFormat(pattern = "Format that needs to be converted"). For example:

@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date birthday;

When using @DateTimeFormat annotation, you need to note that the format specified by pattern corresponds to the format of the passed parameters. If the format does not correspond, an exception may be thrown.

Use ControllerAdvice with initBinder

When the controller is circumcised, you can use initBinder for time formatting. Create a new InitBinderDateController class and format the global time parameter:

@ControllerAdvice
public class InitBinderDateController {
    /**
      * Automatically convert the date format string passed by the foreground to the time type
      * [The parameters modified by @RequestBody annotation cannot be blocked]
      */
    @InitBinder("date")
    public void initBinder(WebDataBinder binder) {
        // Date type conversion        //        DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //        (,new CustomDateEditor(dateFormat, true));
        //       ("test");
        // LocalDateTime Type Conversion        (, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                if (!(text)) {
                    setValue((text, ("yyyy-MM-dd HH:mm:ss")));
                }
            }
        });
    }
}

Backend global settings

Global request date format conversion can be implemented by configuring the backend. For example, configure in a configuration file:

spring:
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8

Or use configuration class method, suitable for both front and back ends to interact in json format. You only need to use @Configuration to define a configuration class and inject two beans to complete the global date response formatting process.

@Configuration
public class LocalDateTimeSerializerConfig {
    private static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
    @Bean
    public LocalDateTimeSerializer localDateTimeSerializer() {
        return new LocalDateTimeSerializer((YYYY_MM_DD_HH_MM_SS));
    }
    @Bean
    public LocalDateTimeDeserializer localDateTimeDeserializer() {
        return new LocalDateTimeDeserializer((YYYY_MM_DD_HH_MM_SS));
    }
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return builder -> {
            (, localDateTimeSerializer());
            (, localDateTimeDeserializer());
        };
    }
}

The output date format of the interface is a time stamp

In Spring Boot, the steps to implement the interface output date format as a timestamp are as follows:

  • Configuring date formatter: In Spring Boot's configuration file, we can configure a date formatter to format dates as timestamps. The following configuration can be added in (or): =unix.
  • Defining entity class: We first need to define an entity class to represent the date field that needs to be output:
public class MyEntity {
    private Date date;
    // getter and setter
}
  • Writing a controller: Next, we need to write a controller class that handles interface requests and returns the timestamp form of the date field. We can use the @JsonFormat annotation to specify how the date field is formatted. Here is a simple example:
@RestController
public class MyController {
    @GetMapping("/entity")
    public MyEntity getEntity() {
        MyEntity entity = new MyEntity();
        (new Date());
        return entity;
    }
}
  • Test interface: After starting the Spring Boot application, we can access the /entity interface to get the timestamp form of the date field. You can use tools such as Postman or browser to test it.

GET /entity HTTP/1.1

Host: localhost:8080

The response result will be a JSON format object, where the date field will be represented as a timestamp. For example:

{
    "date": 1678912345678
}

This is the end of this article about several commonly used interface date formatting methods for SpringBoot. For more related SpringBoot interface date formatting content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!