springboot项目中字符串与date类型的转换

  1. ajax传时间格式字符串,后台用Date类型接参,加注解
    @DateTimeFormat(pattern = “yyyy-MM-dd HH:mm:ss”)

  2. 数据库中取出date类型数据,返回前端,返回的是毫秒数,加注解可以转为对应格式
    @JsonFormat(pattern = “yyyy-MM-dd HH:mm:ss”,timezone = “GMT+8”)
    其中,timezone为时区设置,否则有时差

  3. 将字符串直接转Date类型对象时,使用SimpleDateFormat类
    String str = “1000-01-01 00:00:00”;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
    Date date = simpleDateFormat.parse(str);
    注意
    mysql中datetime类型支持的范围是’1000-01-01 00:00:00’ to ‘9999-12-31 23:59:59’,若要设置0000-00-00 00:00:00,插入的数据会变为0002-11-30 00:00:00。
    时间不匹配时,修改时区代码为
    TimeZone tz = TimeZone.getTimeZone(“ETC/GMT-8”);
    TimeZone.setDefault(tz);

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以为您介绍如何在 Spring Boot 项目实现 Converter 接口,自定义类型转换器。 首先,您需要创建一个类来实现 Converter 接口,并重写其的 convert() 方法。在 convert() 方法,您可以编写自定义转换逻辑,将一个类型转换为另一个类型。 举个例子,比如您需要将一个字符串转换为一个自定义的日期类型。您可以编写如下的代码: ```java import java.text.SimpleDateFormat; import java.util.Date; import org.springframework.core.convert.converter.Converter; public class StringToDateConverter implements Converter<String, Date> { private static final String DATE_FORMAT = "yyyy-MM-dd"; @Override public Date convert(String source) { try { SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT); return dateFormat.parse(source); } catch (Exception e) { return null; } } } ``` 在上面的代码,我们实现了一个将字符串转换为日期类型转换器。在 convert() 方法,我们使用 SimpleDateFormat 类将字符串转换为日期类型。如果转换失败,我们返回 null。 接下来,您需要在 Spring Boot 项目注册这个转换器。您可以在配置类添加如下的代码: ```java import org.springframework.context.annotation.Configuration; 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.addConverter(new StringToDateConverter()); } } ``` 在上面的代码,我们创建了一个 WebMvcConfigurer 配置类,并重写了其的 addFormatters() 方法。在 addFormatters() 方法,我们将我们自定义的转换器实例添加到了 FormatterRegistry 。 现在,我们已经成功地实现了一个自定义的类型转换器,并将其注册到了 Spring Boot 项目。当我们需要将一个字符串转换为日期类型时,Spring Boot 将自动调用我们实现的转换器。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值