在 Java Spring Boot 中,处理时间格式通常涉及到两种常见的需求:请求和响应中的时间格式化,以及将时间格式化为 JSON 或其他数据格式。以下是一些常用的方法和注解来解决这些问题:

1. 使用 @JsonFormat 注解

如果你使用的是 Jackson 进行 JSON 序列化和反序列化,可以使用 @JsonFormat 注解来指定日期和时间的格式。这个注解可以应用于字段、方法或者类上。

import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;

public class MyEntity {
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
    private Date myDate;

    // getters and setters
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
2. 使用 @DateTimeFormat 注解

@DateTimeFormat 注解通常用于 Spring MVC 中的请求参数格式化。它可以指定请求中日期时间参数的格式。这个注解主要用于在 Controller 的参数中应用。

import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;

public class MyController {

    @GetMapping("/example")
    public ResponseEntity<String> example(
        @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date date) {
        // Use the date parameter
        return ResponseEntity.ok("Date received: " + date);
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
3. 使用 LocalDate, LocalDateTime, 和 ZonedDateTime

在 Spring Boot 2.1+ 及更高版本中,支持 Java 8 的 java.time 包。你可以使用 LocalDate, LocalDateTime, 和 ZonedDateTime 来处理日期和时间,并且这些类型的格式化可以通过 @JsonFormat 注解或配置全局的 ObjectMapper 来完成。

配置全局日期时间格式

你可以通过配置 ObjectMapper 来设置全局的日期时间格式。在 @Configuration 注解的配置类中进行配置:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.format.datetime.DateFormatterRegistrar;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.time.format.DateTimeFormatter;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        return mapper;
    }

    @Override
    public void addFormatters(FormatterRegistry registry) {
        DateFormatterRegistrar registrar = new DateFormatterRegistrar();
        registrar.setFormatter(new DateFormatter("yyyy-MM-dd HH:mm:ss"));
        registrar.registerFormatters(registry);
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
4. 使用 @RequestBody@ResponseBody

在处理请求体(@RequestBody)或响应体(@ResponseBody)中的日期时间格式时,可以通过 JSON 的序列化和反序列化配置来确保格式的一致性。例如,可以在 @RestController 中使用 @RequestBody 注解自动处理 JSON 请求体。

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class MyRestController {

    @PostMapping("/date")
    public ResponseEntity<String> receiveDate(@RequestBody MyEntity myEntity) {
        // Process the myEntity object
        return ResponseEntity.ok("Date received: " + myEntity.getMyDate());
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
5. 自定义格式化器

如果需要更复杂的格式化需求,可以创建自定义的格式化器并注册它。

import org.springframework.format.Formatter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class CustomDateFormatter implements Formatter<Date> {

    private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public Date parse(String text, Locale locale) throws ParseException {
        return dateFormat.parse(text);
    }

    @Override
    public String print(Date object, Locale locale) {
        return dateFormat.format(object);
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.

然后在配置中注册自定义格式化器:

import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addFormatter(new CustomDateFormatter());
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

以上这些方法和注解可以帮助在 Spring Boot 应用中处理各种日期和时间格式化需求。选择适合的需求的方法来确保应用能够正确地处理时间数据。