如何让接口支持时间格式化字符串自动转 LocalDateTime


title: 如何让接口支持时间格式化字符串自动转 LocalDateTime
id: 20240810203052
aliases:
date: 2024-08-10 20:30:52
tags:

  • spring
  • ConversionService

需求:支持时间格式化字符串自动转 LocalDateTime

GET http://localhost:8080/doc20240810/test?time=2024-08-10 16:53:03
  
@RestController  
@RequestMapping("doc20240810")  
@RequiredArgsConstructor  
@Slf4j  
public class DemoController {  
    @GetMapping("test")  
    public String test(@RequestParam LocalDateTime time) {  
        return MessageFormat.format("成功获取到time={0}", time);  
    }  
}

如何让Spring 支持对于以上场景的支持?

1、实现 org.springframework.core.convert.converter.Converter 接口,用于实现对于 String ==> LocalDateTime 的转换
public class LongToLocalDateTime implements Converter<Long, LocalDateTime> {  
    @Override  
    public LocalDateTime convert(Long str) {  
        return LocalDateTime.ofInstant(Instant.ofEpochMilli(str), ZoneId.systemDefault());  
    }  
}
2、在 WebMvcConfigurer 注册新的 StringToLocalDate
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {  
    @Override  
    public void addFormatters(FormatterRegistry registry) {  
        registry.addConverter(new StringToLocalDateTime());
    }  
}
3、测试

image.png

END

以上只是简单的讲诉了 Spring 类型转换的使用方法,可以解决的具体问题;我后续将会学习关于 Spring 类型转换的相关组件的内容,可以关注后续文章
在此强烈推荐 [YourBatman 大佬的文章](#[YourBatman]-Spring类型转换 (qq.com))

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值