前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【小家Spring】@DateTimeFormat和@NumberFormat以及@JsonFormat的使用

【小家Spring】@DateTimeFormat和@NumberFormat以及@JsonFormat的使用

作者头像
YourBatman
发布2019-09-03 16:43:22
2.7K0
发布2019-09-03 16:43:22
举报
文章被收录于专栏:BAT的乌托邦BAT的乌托邦
前言

数据格式化,从本质上讲属于数据转换的范畴。Spring就是基于数据转换框架植入“格式化”功能的。

时间是一个比较常用的类型。显示的时候通常是以String显示的。如果前端参数,前端人员也希望用String作为参数。而使用注解处理这些转换,显得就会特别的优雅

注解介绍:

@DatetimeFormat(pattern=“yyyy-MM-dd”)是将String转换成Date,一般前台给后台传值时用 @JsonFormat(pattern=“yyyy-MM-dd”) 将Date转换成String 一般后台传值给前台时 此处注意:@JsonFormat会让时间以0区时间显示。如果直接使用会少了8小时(我所在的是北京时区)修改为 @JsonFormat(pattern=“yyyy-MM-dd”,timezone=“GMT+8”) @NumberFormat(pattern="#,###") 用来格式化货币(这样前端得传形如1,000。而不能是1000了哟,其实这个用得一般还比较少一点)

例子
代码语言:javascript
复制
public class Student {
    private String name;
    private Integer gender;
    @DateTimeFormat(pattern="yyyy-MM-dd")
    private Date birth;
    @NumberFormat(pattern="#,###")
    private Integer salary;
    

    public Student(String name, Integer gender, Date birth, Integer salary) {
        super();
        this.name = name;
        this.gender = gender;
        this.birth = birth;
        this.salary = salary;
    }
}

在提交时就可以时间格式写成这样

这里写图片描述
这里写图片描述

备注:如果是Java8类型的日期。比如LocalDate、LocalTime、LocalDateTime。一般借用@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)方式。但是具体情况具体在分析

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018年09月06日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • 注解介绍:
  • 例子
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档