@DateTimeFormat
是 Spring 框架中的一个注解,用于指定日期和时间字符串的格式,以便在数据绑定过程中将字符串转换为 java.util.Date
、java.util.Calendar
、java.time.LocalDate
、java.time.LocalTime
、java.time.LocalDateTime
等类型。这个注解通常用于控制器方法的参数上,以便在处理 HTTP 请求时自动将请求参数转换为相应的日期和时间类型。
使用详情
1. 基本用法
在控制器方法的参数上使用 @DateTimeFormat
注解,指定日期和时间的格式。
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDate;
import java.time.LocalDateTime;
@RestController
public class DateController {
@GetMapping("/date")
public String getDate(@RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE