Java中Http请求Get和Post对LocalDateTime的格式化

需求描述:
WEB项目中经常遇到前台以Get或者Post方式传时间值到后台,后台采用日期类进行参数接收。

Java8日期类

java8为了方便日期处理,引进了日期类LocalDateLocalDateTime,提供了很多方法进行日期的操作,同时也提供了线程安全的格式化类DateTimeFormatter

 /** 
 * @implSpec
 * This class is immutable and thread-safe.
 *
 * @since 1.8
 */
public final class LocalDateTime {...}

Get方式传参格式化

1. @DateTimeFormat 方式

注: @DateTimeFormat为Spring带的注解


// 注解可直接作用在方法参数上
@GetMapping("/product/list")
public IPage<Product> listProducts(@DateTimeFormat(pattern = "yyyy-MM-dd") LocalDateTime startTime,
                                   @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDateTime endTime) {
    // do something
    return null;
}
    
/**
 * 产品查询参数
 *
 * @author tangjizhouchn@foxmail.com
 * @date 2019/10/16
 */
@Data
public class ProductQuery {

    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private LocalDateTime startTime;
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private LocalDateTime endTime;

}

// 注解可作用对象中的属性上
@GetMapping("/product/list")
public IPage<Product> listProducts(ProductQuery query) {
    // do something
    return null;
}

此种方式需要在每个参数上进行配置,比较麻烦。

2. WebDataBinder方式(推荐)
/**
 * 天猫系统controller切面
 *
 * @author tangjizhouchn@foxmail.com
 * @date 2019-08-18
 */
@Slf4j
@ControllerAdvice
public class GlobalControllerAdvice {

    @InitBinder
    public void initBinder(WebDataBinder webDataBinder) {
        webDataBinder.registerCustomEditor(LocalDate.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                setValue(LocalDate.parse(text, DateTimeFormatter.ISO_DATE));
            }
        });
        webDataBinder.registerCustomEditor(LocalDateTime.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                setValue(LocalDateTime.parse(text, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            }
        });
    }
}

Post方式传参格式化

1. @JsonFormat方式

注:@JsonFormat为Jackson带的注解

@Data
public class ProductDTO {
	// LocalDate可以不用配置,默认格式就是 "yyyy-MM-dd"
	// LocalDateTime需要配置,并需要配置到分或者秒 "yyyy-MM-dd HH:mm"
    @JsonFormat(pattern = "yyyy-MM-dd")
    private LocalDate startTime;
    @JsonFormat(pattern = "yyyy-MM-dd")
    private LocalDate endTime;
    
}

此种方式配置需要在每个DTO对象上进行配置,比较麻烦。

2. 全局配置方式(推荐)
/**
 * 系统通用简单配置
 *
 * @author tangjizhouchn@foxmail.com
 * @date 2019/10/16
 */
@Configuration
public class TmallConfiguration {

    /**
     * 此方式可以灵活配置任意类型的序列化反序列化
     */
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer builderCustomizer() {
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        DateTimeFormatter dateTimeSerializeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        DateTimeFormatter dateTimeDeserializeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        return builder -> {
            builder.serializerByType(Long.class, ToStringSerializer.instance);
            builder.serializerByType(LocalDate.class, new LocalDateSerializer(dateFormatter));
            builder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(dateTimeSerializeFormatter));
            builder.deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer(dateTimeDeserializeFormatter));
        };
    }
}



  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值