SpringBoot时间出入参格式化-3:全局Timestamp出入参

上一篇中使用的是全局使用字符串处理时间参数。本文提供第三种处理方式:使用全局时间戳方式处理入参时间,如入参:1657096088961,这种方式同全局字符串处理方式类似,置于两者用哪种,看个人所需。

  • 优点:参数上不需要加任何注解,即可全局统一入参格式&出参格式
  • 缺点:时间报文不可读
传送链接:
  • 日期时间对象全注解方式出入参:https://blog.csdn.net/qq_35614522/article/details/125683621
  • 日期时间对象全局字符串出入参:https://blog.csdn.net/qq_35614522/article/details/125684066

代码实现:

定义相关常量:TimeConstants

package com.vip.tools.format.timestamp.constant;/*** 时间转换常量** @author wgb* @date 2021/1/15 15:00*/
public interface TimeConstants {/*** 默认时间格式正则*/String LOCAL_TIME_REGULAR = "^\\d{1,2}:\\d{1,2}:\\d{1,2}$";/*** 时间戳正则*/String TIMESTAMP_REGULAR = "^\\d{13}$";/*** 默认时间格式*/String DEFAULT_TIME_FORMAT = "HH:mm:ss";
}

转换类核心代码:TimestampToDateConverter

import com.vip.tools.format.timestamp.constant.TimeConstants;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.lang.Nullable;import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.util.Date;/*** 自定义类型转换, @RequestParam/@PathVariable的日期字符串转换对应日期类型** @author wgb* @date 2021/01/14 15:57*/
@Configuration
public class TimestampToDateConverter<T> {@Bean(name = "localDateTimeConverter")public Converter<String, LocalDateTime> localDateTimeConverter() {return new Converter<String, LocalDateTime>() {@Overridepublic LocalDateTime convert(@Nullable String source) {if(StringUtils.isBlank(source)){return null;}if(!source.matches(TimeConstants.TIMESTAMP_REGULAR)){throw new IllegalArgumentException("Invalid Time Value of Type String:" + source);}return new Date(Long.parseLong(source)).toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime();}};}@Bean(name = "localDateConverter")public Converter<String, LocalDate> localDateConverter() {return new Converter<String, LocalDate>() {@Overridepublic LocalDate convert(@Nullable String source) {if(StringUtils.isBlank(source)){return null;}if(!source.matches(TimeConstants.TIMESTAMP_REGULAR)){throw new IllegalArgumentException("Invalid Time Value of Type String:" + source);}return new Date(Long.parseLong(source)).toInstant().atOffset(ZoneOffset.of("+8")).toLocalDate();}};}@Bean(name = "localTimeConverter")public Converter<String, LocalTime> localTimeConverter() {return new Converter<String, LocalTime>() {@Overridepublic LocalTime convert(@Nullable String source) {if(StringUtils.isBlank(source)){return null;}if(!source.matches(TimeConstants.LOCAL_TIME_REGULAR)){throw new IllegalArgumentException("Invalid Time Value of Type String:" + source);}return LocalTime.parse(source);}};}@Bean(name = "dateConverter")public Converter<String, Date> dateConverter() {return new Converter<String, Date>() {@Override@SneakyThrowspublic Date convert(@Nullable String source) {if (StringUtils.isBlank(source)) {return null;}if (!source.matches(TimeConstants.TIMESTAMP_REGULAR)) {throw new IllegalArgumentException("Invalid Time Value of Type String:" + source);}return new Date(Long.parseLong(source));}};}}

Jackson参数转换器配置

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import com.vip.tools.format.timestamp.constant.TimeConstants;
import lombok.SneakyThrows;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;/*** 使用官方自带的json格式类库* 可以处理多种格式化方式,这里只使用了时间格式化** @author wgb* @date 2020/11/25 18:07*/
public class JacksonHttpMessageConverter extends MappingJackson2HttpMessageConverter {public JacksonHttpMessageConverter() {handleDateTime();}private void handleDateTime() {ObjectMapper objectMapper = this.getObjectMapper();// Date出入参格式化objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);// Java8时间格式化JavaTimeModule javaTimeModule = new JavaTimeModule();// 出参格式化javaTimeModule.addSerializer(LocalDateTime.class, new MyLocalDateTimeSerializer());javaTimeModule.addSerializer(LocalDate.class, new MyLocalDateSerializer());javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(TimeConstants.DEFAULT_TIME_FORMAT)));// 入参格式化javaTimeModule.addDeserializer(LocalDateTime.class, new MyLocalDateTimeDeserializer());javaTimeModule.addDeserializer(LocalDate.class, new MyLocalDateDeserializer());javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(TimeConstants.DEFAULT_TIME_FORMAT)));// 把“忽略重复的模块注册”禁用,否则下面的注册(LocalDateTime)不生效objectMapper.disable(MapperFeature.IGNORE_DUPLICATE_MODULE_REGISTRATIONS);objectMapper.registerModule(javaTimeModule);// 然后再设置为生效,避免被其他地方覆盖objectMapper.enable(MapperFeature.IGNORE_DUPLICATE_MODULE_REGISTRATIONS);// 设置格式化内容this.setObjectMapper(objectMapper);}/*** LocalDateTime序列化为时间戳*/public static class MyLocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {@Override@SneakyThrowspublic void serialize(LocalDateTime localDateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) {jsonGenerator.writeNumber(localDateTime.toInstant(ZoneOffset.ofHours(8)).toEpochMilli());}}/*** LocalDate序列化时为时间戳*/public static class MyLocalDateSerializer extends JsonSerializer<LocalDate> {@Override@SneakyThrowspublic void serialize(LocalDate localDate, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) {jsonGenerator.writeNumber(localDate.atStartOfDay(ZoneOffset.ofHours(8)).toInstant().toEpochMilli());}}/*** 时间戳反序列化为LocalDateTime*/public static class MyLocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {@Override@SneakyThrowspublic LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) {return LocalDateTime.ofEpochSecond(jsonParser.getLongValue() / 1000, 0, ZoneOffset.ofHours(8));}}/*** 时间戳反序列化为LocalDate*/public static class MyLocalDateDeserializer extends JsonDeserializer<LocalDate> {@Override@SneakyThrowspublic LocalDate deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) {return new Date(jsonParser.getLongValue()).toInstant().atOffset(ZoneOffset.of("+8")).toLocalDate();}}}

WebMvcConfiguration

import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Date;
import java.util.List;/*** WebMvcConfiguration** @author wgb* @date 2020/11/25 16:45*/
@Configuration
@RequiredArgsConstructor
public class WebMvcConfiguration extends WebMvcConfigurationSupport {private final Converter<String, LocalDateTime> localDateTimeConverter;private final Converter<String, LocalDate> localDateConverter;private final Converter<String, LocalTime> localTimeConverter;private final Converter<String, Date> dateConverter;/*** 入参时间格式化*/@Overrideprotected void addFormatters(FormatterRegistry registry) {registry.addConverter(localDateTimeConverter);registry.addConverter(localDateConverter);registry.addConverter(localTimeConverter);registry.addConverter(dateConverter);}/*** extends WebMvcConfigurationSupport* 以下 spring-boot: jackson时间格式化 配置 将会失效* spring.jackson.time-zone=GMT+8* spring.jackson.date-format=yyyy-MM-dd HH:mm:ss* 原因: 会覆盖 @EnableAutoConfiguration 关于 WebMvcAutoConfiguration 的配置*/@Overridepublic void configureMessageConverters(List<HttpMessageConverter<?>> converters) {super.configureMessageConverters(converters);JacksonHttpMessageConverter converter = new JacksonHttpMessageConverter();converters.add(converter);// 添加二进制数组转换器:用以文件下载时二进制流的响应converters.add(new ByteArrayHttpMessageConverter());}}

开始写测试代码

DTO

import lombok.Data;import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Date;/*** description** @author wgb* @date 2021/1/14 15:57*/
@Data
public class TinyDTO {/*** date*/private Date date;/*** localDate*/private LocalDate localDate;/*** localDateTime*/private LocalDateTime localDateTime;/*** localTime*/private LocalTime localTime;/*** 附加属性*/private String name;}

controller

import com.vip.tools.format.timestamp.dto.TinyDTO;
import com.vip.tools.normal.UuidUtils;
import org.springframework.web.bind.annotation.*;import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Date;/*** 时间格式化 控制器** @author wgb* @date 2021/1/15 13:25*/
@RestController
@RequestMapping(value = "/timestamp_format")
public class TimestampDateFormatController {/*** 格式化测试** @return*/@PostMapping("/test")public TinyDTO format(@RequestParam Date date, @RequestParam LocalDate localDate, @RequestParam LocalDateTime localDateTime, @RequestParam LocalTime localTime, @RequestBody TinyDTO dto) {System.out.println(date);System.out.println(localDate);System.out.println(localDateTime);System.out.println(localTime);System.out.println(dto);return dto;}}

测试

URL: http://localhost:9600/timestamp_format/test?date=1610595117250&localDate=1610595117250&localDateTime=1610595117250&localTime=12:00:23
Body参数:

{"date": 1610595117250,"localDate": 1610595117250,"localDateTime": 1610595117250,"localTime": "23:59:59","name": "TEST"
}

控制台打印:

Thu Jan 14 11:31:57 CST 2021
2021-01-14
2021-01-14T11:31:57.250
12:00:23
TinyDTO(date=Thu Jan 14 11:31:57 CST 2021, localDate=2021-01-14, localDateTime=2021-01-14T11:31:57, localTime=23:59:59, name=TEST)

响应结果:

{"date": 1610595117250,"localDate": 1610553600000,"localDateTime": 1610595117000,"localTime": "23:59:59","name": "TEST"
}

日期对象全局字符串出入参配置完成。
总结: 以上介绍了三种时间参数转换的方式,全注解方式是最不推荐的,推荐使用全局字符串转换方式,这样便于前端格式化日期格式,以及时间可阅读,全局时间戳转换方式按需使用。

SpringBoot日期时间全局出入参格式化-3:全局Timestamp出入参相关推荐

  1. uni-app获取当前具体日期时间并将其格式化

    uni-app获取当前具体日期时间并将其格式化 getTime:function(){ var date = new Date(), year = date.getFullYear(), month ...

  2. python按年月日输出字符串_python日期时间转为字符串或者格式化输出的实例

    python日期时间转为字符串或者格式化输出的实例 如下所示: 年月日时分秒 >>> print datetime.datetime.now().strftime("%Y- ...

  3. oracle2周后日期,ORACLE日期时间及数字的格式化参数大全

    SSSSS 返回自午夜到指定时间共逝去的秒数(范围:0-86399) 例如: SQL> select to_char(sysdate,¨sssss¨) from dual; TO_CHAR(SY ...

  4. asp php时间格式,ASP_asp格式化日期时间格式的代码,' ====================================== - phpStudy...

    asp格式化日期时间格式的代码 ' ============================================ ' 格式化时间(显示) ' 参数:n_Flag ' 1:"yyy ...

  5. bat批处理开发-wifi联网系列(5):wifi稳定性分析之日期时间比较及奇特数字的坑

    公司wifi很不稳定,编写了个wifi断网后自动重连的批处理,主要包括:可用wifi查询.联网.wifi切换感知.自动检测及掉线重连,网络状态分析等功能. 上篇:bat批处理开发-wifi联网系列(4 ...

  6. bootstrap日期时间控件

    datetime控件 Bootstrap的日期时间控件,使用非常的简单. 首先,添加日期时间控件的引用 @*datetime控件*@<link href="~/Content/Boot ...

  7. Day640.Java 8的日期时间类问题 -Java业务开发常见错误

    Java 8的日期时间类问题 Hi,阿昌来也! 今天记录分享的是Java 8的日期时间类问题 在 Java 8 之前,我们处理日期时间需求时,使用 Date.Calender 和 SimpleDate ...

  8. JS日期时间比较大小(绝对干货)

    普通日期时间比较 泛指格式相同的日期时间 var date1 = new Date("2020-3-15"); var date2 = new Date("2020-2- ...

  9. MySQL 日期时间类型精确到毫秒

    MySQL 常用的日期时间类型常用的是datetime.timestamp.其中datetime占用5个字节(有些文档中说占用8个字节是不对的,默认也不会保存毫秒). ​​​​​​​ DATETIME ...

最新文章

  1. spring-注入list集合对象(值是对象)
  2. 微信实现定位城市并获取城市编码
  3. 从大学到结婚,我和小云的这13年
  4. 接口测试(二)--APP抓包
  5. php烟花效果,用p5.js制作烟花特效的示例代码
  6. liunx中安装软件的几种方式
  7. 逻辑卷管理(LVM)
  8. 那天柠檬果第一次成熟,真像是几经磨难摘来的“仙人果”。
  9. 服务器显示屏 超出工作频率范围,如何解决显示器出错提示:超出工作频率范围...
  10. 游戏开发 | 基于 EasyX 库开发经典90坦克大战游戏
  11. UEditor自定义表情包
  12. 中南计算机专业数学复试分数线,2019年中南大学考研复试分数线已公布
  13. 我国数学家丁小平先生在微积分研究领域所取得的成就
  14. ZJM与生日礼物【字典树】
  15. Pygame键盘输入和鼠标操作
  16. 分享一款快速、免费抠图工具——凡科快图
  17. 华为员工必选题:做奋斗者,还是劳动者?
  18. 苹果6plus性能测试软件,iPhone 6、iPhone6 Plus性能测试
  19. java计算机毕业设计研究生推免系统源码+数据库+系统+lw文档+部署
  20. Python笔记:纯python操作矩阵:进行矩阵的相乘运算

热门文章

  1. Hallucination Improves Few-Shot Object Detection
  2. 实训第六天:搜索框布局及功能实现,实现上下滑动
  3. Google Colab免费GPU使用教程,亲测成功!
  4. 计算机类学术论文写作中提高效率的小工具
  5. CodeIgniter 框架路由
  6. Android wifi探究二:Wifi framework层源码分析
  7. java环境的安装及配置
  8. 麦子学院深度学习基础 —— 机器学习 —— 最近邻规则分类 KNN 算法
  9. Python 调用百度通用翻译接口
  10. 在C#中保存Bouncy Castle生成的密钥对