详细分析Java中的@JsonFormat注解和@DateTimeFormat注解

这篇具有很好参考价值的文章主要介绍了详细分析Java中的@JsonFormat注解和@DateTimeFormat注解。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

前言

下文中涉及MybatisPlus的逻辑删除的知识,可看我之前这篇文章:详细讲解MybatisPlus实现逻辑删除

对应的Navicat设置数据库最新时间可看我这篇文章:Navicat 设置时间默认值(当前最新时间)


为了使 @JsonFormat 生效,项目必须引入 Jackson 库的相关依赖:
(如果是springboot项目,可不用配置,本身spring-boot-start-web依赖已包含)

<!-- JSON工具类 -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.12.6</version>
</dependency>

摘要:

  1. 注解@JsonFormat主要是后端到前端的时间格式的转换

  2. 注解@DateTimeFormat主要是前端到后端的时间格式的转换

1. @JsonFormat注解

@JsonFormat 是 Jackson 库中的注解,用于在序列化和反序列化过程中控制日期和时间的格式。

该注解提供了一种自定义日期和时间格式的方式,以确保在 JSON 数据和 Java 对象之间正确地进行转换。

以下是 @JsonFormat 注解的一些主要概念和功能:

  • pattern(模式): 通过 pattern 属性,您可以指定日期和时间的格式。
    例如,如果要将日期格式设置为"yyyy-MM-dd",可以使用 @JsonFormat(pattern = "yyyy-MM-dd")

  • timezone(时区): 使用 timezone 属性可以指定日期和时间的时区。这对于确保正确地处理跨时区的日期数据很重要。

  • locale(区域设置): 通过 locale 属性,您可以指定用于格式化的区域设置,以便支持不同的语言和地区。

  • shape(形状): shape 属性定义了序列化后的日期表示形式。例如,您可以将日期表示为字符串或时间戳。

  • with(特定类型的格式): 使用 with 属性,您可以为不同的 Java 类型指定不同的格式。这对于处理不同类型的日期数据非常有用。

下面是一个简单的 Java 类示例,演示如何使用 @JsonFormat 注解:

import com.fasterxml.jackson.annotation.JsonFormat;

import java.util.Date;

public class MyObject {

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+00:00")
    private Date myDate;

    // 其他属性和方法

    public Date getMyDate() {
        return myDate;
    }

    public void setMyDate(Date myDate) {
        this.myDate = myDate;
    }
}

在这个例子中,myDate 属性使用了 @JsonFormat 注解,指定了日期的格式和时区。

当这个对象被序列化成 JSON 或者从 JSON 反序列化时,将使用指定的格式来处理日期数据。

2. @DateTimeFormat注解

@DateTimeFormat 是 Spring 框架中用于处理日期和时间格式的注解。

它通常与 @RequestMapping@RequestParam 等注解一起使用,以指定接收或发送日期时间参数时的格式。

以下是 @DateTimeFormat 注解的一些主要概念和功能:

  • pattern(模式): 通过 pattern 属性,您可以指定日期和时间的格式。
    @JsonFormat 不同,@DateTimeFormat 是专门为 Spring 框架设计的,用于在 Web 请求中处理日期参数。

  • iso(ISO标准格式): 使用 iso 属性可以指定使用 ISO 标准的日期时间格式。
    例如,@DateTimeFormat(iso = ISO.DATE) 表示日期部分采用标准日期格式。

  • style(样式): style 属性定义了预定义的日期和时间格式。
    有三种样式可用:DEFAULTSHORTMEDIUMLONGFULL。这些样式在不同的地区设置下有不同的显示效果。

  • lenient(宽松解析): lenient 属性用于指定是否宽松解析日期。
    如果设置为 true,则在解析日期时会尽量接受不严格符合格式的输入。

  • patternResolver(模式解析器): patternResolver 属性允许您指定自定义的模式解析器,以便更灵活地处理日期时间格式。

下面是一个简单的 Spring MVC 控制器示例,演示如何使用 @DateTimeFormat 注解:

import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("/date")
public class DateController {

    @RequestMapping("/processDate")
    public String processDate(@RequestParam("myDate") @DateTimeFormat(pattern = "yyyy-MM-dd") Date myDate) {
        // 处理日期逻辑
        return "Received date: " + myDate;
    }
}

processDate 方法接收一个名为 myDate 的参数,并使用 @DateTimeFormat 注解指定了日期的格式。

当请求中包含名为 myDate 的参数时,Spring 将自动将参数解析为 Date 类型,并应用指定的格式。

3. Demo

为了做好例子的前提,需要配置好数据库以及代码信息。

数据库相应的信息如下:

数据库类型为datetime或者timestamp,根据时间戳更新:
详细分析Java中的@JsonFormat注解和@DateTimeFormat注解,java,java,Datetime,JsonFormat,DateTimeFormat

代码信息主要如下:(实体类)

@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("test_student")
public class student{

    @TableId(value = "id", type = IdType.AUTO)
    private int id;
    private String username;
    // 其他字段...
    private Date time;

    @TableLogic
    private Integer deleteFlag;

}

service类:

public interface StudentService extends IService<student> {
    // 这里可以自定义一些业务方法
}

实现类:

@Service
public class StrudentServiceimpl extends ServiceImpl<StudentMapper, student> implements StudentService {
    // 这里可以实现自定义的业务方法
}

Mapper类:

@Mapper
public interface StudentMapper extends BaseMapper<student> {
    // 这里可以自定义一些查询方法
}

3.1 无注解

对应的实体类在Date中没有相关的注解:private Date time;

对应没有注解的时候,测试类输出结果如下:time=Thu Jan 11 21:02:06 CST 2024

3.2 有注解

这两者的注解一般联合使用

@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone="GMT+8")
private Date time;

一般系统都是前后交互

对此总结如下:

  • 注解@JsonFormat主要是后端到前端的时间格式的转换

  • 注解@DateTimeFormat主要是前端到后端的时间格式的转换

4. 拓展

常用的配置如下:

详细分析Java中的@JsonFormat注解和@DateTimeFormat注解,java,java,Datetime,JsonFormat,DateTimeFormat

对应的时间配置可以使用该类进行拓展:文章来源地址https://www.toymoban.com/news/detail-818662.html

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

import java.text.ParseException;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAccessor;
import java.time.temporal.TemporalAmount;
import java.time.temporal.TemporalQuery;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import org.springframework.util.Assert;

public class DateUtil {
    public static final String PATTERN_DATETIME = "yyyy-MM-dd HH:mm:ss";
    public static final String PATTERN_DATETIME_MINI = "yyyyMMddHHmmss";
    public static final String PATTERN_DATE = "yyyy-MM-dd";
    public static final String PATTERN_TIME = "HH:mm:ss";
    public static final ConcurrentDateFormat DATETIME_FORMAT = ConcurrentDateFormat.of("yyyy-MM-dd HH:mm:ss");
    public static final ConcurrentDateFormat DATETIME_MINI_FORMAT = ConcurrentDateFormat.of("yyyyMMddHHmmss");
    public static final ConcurrentDateFormat DATE_FORMAT = ConcurrentDateFormat.of("yyyy-MM-dd");
    public static final ConcurrentDateFormat TIME_FORMAT = ConcurrentDateFormat.of("HH:mm:ss");
    public static final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    public static final DateTimeFormatter DATETIME_MINI_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
    public static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    public static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("HH:mm:ss");

    public DateUtil() {
    }

    public static Date now() {
        return new Date();
    }

    public static Date plusYears(Date date, int yearsToAdd) {
        return set(date, 1, yearsToAdd);
    }

    public static Date plusMonths(Date date, int monthsToAdd) {
        return set(date, 2, monthsToAdd);
    }

    public static Date plusWeeks(Date date, int weeksToAdd) {
        return plus(date, Period.ofWeeks(weeksToAdd));
    }

    public static Date plusDays(Date date, long daysToAdd) {
        return plus(date, Duration.ofDays(daysToAdd));
    }

    public static Date plusHours(Date date, long hoursToAdd) {
        return plus(date, Duration.ofHours(hoursToAdd));
    }

    public static Date plusMinutes(Date date, long minutesToAdd) {
        return plus(date, Duration.ofMinutes(minutesToAdd));
    }

    public static Date plusSeconds(Date date, long secondsToAdd) {
        return plus(date, Duration.ofSeconds(secondsToAdd));
    }

    public static Date plusMillis(Date date, long millisToAdd) {
        return plus(date, Duration.ofMillis(millisToAdd));
    }

    public static Date plusNanos(Date date, long nanosToAdd) {
        return plus(date, Duration.ofNanos(nanosToAdd));
    }

    public static Date plus(Date date, TemporalAmount amount) {
        Instant instant = date.toInstant();
        return Date.from(instant.plus(amount));
    }

    public static Date minusYears(Date date, int years) {
        return set(date, 1, -years);
    }

    public static Date minusMonths(Date date, int months) {
        return set(date, 2, -months);
    }

    public static Date minusWeeks(Date date, int weeks) {
        return minus(date, Period.ofWeeks(weeks));
    }

    public static Date minusDays(Date date, long days) {
        return minus(date, Duration.ofDays(days));
    }

    public static Date minusHours(Date date, long hours) {
        return minus(date, Duration.ofHours(hours));
    }

    public static Date minusMinutes(Date date, long minutes) {
        return minus(date, Duration.ofMinutes(minutes));
    }

    public static Date minusSeconds(Date date, long seconds) {
        return minus(date, Duration.ofSeconds(seconds));
    }

    public static Date minusMillis(Date date, long millis) {
        return minus(date, Duration.ofMillis(millis));
    }

    public static Date minusNanos(Date date, long nanos) {
        return minus(date, Duration.ofNanos(nanos));
    }

    public static Date minus(Date date, TemporalAmount amount) {
        Instant instant = date.toInstant();
        return Date.from(instant.minus(amount));
    }

    private static Date set(Date date, int calendarField, int amount) {
        Assert.notNull(date, "The date must not be null");
        Calendar c = Calendar.getInstance();
        c.setLenient(false);
        c.setTime(date);
        c.add(calendarField, amount);
        return c.getTime();
    }

    public static String formatDateTime(Date date) {
        return DATETIME_FORMAT.format(date);
    }

    public static String formatDateTimeMini(Date date) {
        return DATETIME_MINI_FORMAT.format(date);
    }

    public static String formatDate(Date date) {
        return DATE_FORMAT.format(date);
    }

    public static String formatTime(Date date) {
        return TIME_FORMAT.format(date);
    }

    public static String format(Date date, String pattern) {
        return ConcurrentDateFormat.of(pattern).format(date);
    }

    public static String formatDateTime(TemporalAccessor temporal) {
        return DATETIME_FORMATTER.format(temporal);
    }

    public static String formatDateTimeMini(TemporalAccessor temporal) {
        return DATETIME_MINI_FORMATTER.format(temporal);
    }

    public static String formatDate(TemporalAccessor temporal) {
        return DATE_FORMATTER.format(temporal);
    }

    public static String formatTime(TemporalAccessor temporal) {
        return TIME_FORMATTER.format(temporal);
    }

    public static String format(TemporalAccessor temporal, String pattern) {
        return DateTimeFormatter.ofPattern(pattern).format(temporal);
    }

    public static Date parse(String dateStr, String pattern) {
        ConcurrentDateFormat format = ConcurrentDateFormat.of(pattern);

        try {
            return format.parse(dateStr);
        } catch (ParseException var4) {
            throw Exceptions.unchecked(var4);
        }
    }

    public static Date parse(String dateStr, ConcurrentDateFormat format) {
        try {
            return format.parse(dateStr);
        } catch (ParseException var3) {
            throw Exceptions.unchecked(var3);
        }
    }

    public static <T> T parse(String dateStr, String pattern, TemporalQuery<T> query) {
        return DateTimeFormatter.ofPattern(pattern).parse(dateStr, query);
    }

    public static Instant toInstant(LocalDateTime dateTime) {
        return dateTime.atZone(ZoneId.systemDefault()).toInstant();
    }

    public static LocalDateTime toDateTime(Instant instant) {
        return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
    }

    public static Date toDate(LocalDateTime dateTime) {
        return Date.from(toInstant(dateTime));
    }

    public static Date toDate(final LocalDate localDate) {
        return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
    }

    public static Calendar toCalendar(final LocalDateTime localDateTime) {
        return GregorianCalendar.from(ZonedDateTime.of(localDateTime, ZoneId.systemDefault()));
    }

    public static long toMilliseconds(final LocalDateTime localDateTime) {
        return localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
    }

    public static long toMilliseconds(LocalDate localDate) {
        return toMilliseconds(localDate.atStartOfDay());
    }

    public static LocalDateTime fromCalendar(final Calendar calendar) {
        TimeZone tz = calendar.getTimeZone();
        ZoneId zid = tz == null ? ZoneId.systemDefault() : tz.toZoneId();
        return LocalDateTime.ofInstant(calendar.toInstant(), zid);
    }

    public static LocalDateTime fromInstant(final Instant instant) {
        return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
    }

    public static LocalDateTime fromDate(final Date date) {
        return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
    }

    public static LocalDateTime fromMilliseconds(final long milliseconds) {
        return LocalDateTime.ofInstant(Instant.ofEpochMilli(milliseconds), ZoneId.systemDefault());
    }

    public static Duration between(Temporal startInclusive, Temporal endExclusive) {
        return Duration.between(startInclusive, endExclusive);
    }

    public static Period between(LocalDate startDate, LocalDate endDate) {
        return Period.between(startDate, endDate);
    }

    public static Duration between(Date startDate, Date endDate) {
        return Duration.between(startDate.toInstant(), endDate.toInstant());
    }

    public static String secondToTime(Long second) {
        if (second != null && second != 0L) {
            long days = second / 86400L;
            second = second % 86400L;
            long hours = second / 3600L;
            second = second % 3600L;
            long minutes = second / 60L;
            second = second % 60L;
            return days > 0L ? StringUtil.format("{}天{}小时{}分{}秒", new Object[]{days, hours, minutes, second}) : StringUtil.format("{}小时{}分{}秒", new Object[]{hours, minutes, second});
        } else {
            return "";
        }
    }

    public static String today() {
        return format(new Date(), "yyyyMMdd");
    }

    public static String time() {
        return format(new Date(), "yyyyMMddHHmmss");
    }

    public static Integer hour() {
        return NumberUtil.toInt(format(new Date(), "HH"));
    }
}

到了这里,关于详细分析Java中的@JsonFormat注解和@DateTimeFormat注解的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包赞助服务器费用

相关文章

  • 详细分析Java中的@RequestParam和@RequestBody

    详细分析Java中的@RequestParam和@RequestBody

    该知识点主要来源于SpringMVC:SpringMVC从入门到精通(全) 慢慢作为一名全栈,偶尔看项目使用 @RequestParam 或者 @RequestBody ,对此需要做一个深度的总结,防止混淆 @RequestParam 注解用于从HTTP请求中提取查询参数或表单参数。 其中一些常用的属性参数包括 name 、 defaultValue 和 r

    2024年04月26日
    浏览(9)
  • 详细分析Java中的Optional类以及应用场景

    详细分析Java中的Optional类以及应用场景

    在实战中学习,灵活运用每个操作类,具体如下: 源码主要如下: 大致含义如下: 这是一个容器对象,可能包含或不包含非空值。如果有值存在,isPresent() 方法将返回 true,而 get() 方法将返回该值。 提供了一些依赖于包含值的存在或缺失的其他方法,例如 orElse()(如果值不

    2024年04月27日
    浏览(18)
  • 详细分析Spring中的@Around注解(附Demo)

    详细分析Spring中的@Around注解(附Demo)

    此知识点都来源于项目实战,对此进行科普总结,使得之后项目游刃有余 对于Spring的基本知识,推荐阅读: Spring框架从入门到学精(全) java框架 零基础从入门到精通的学习路线 附开源项目面经等(超全) 在Java中, @Around 注解通常与AspectJ框架一起使用,用于定义一个环绕

    2024年04月11日
    浏览(11)
  • 【Java中的Thread线程的简单方法介绍和使用详细分析】

    【Java中的Thread线程的简单方法介绍和使用详细分析】

    提示:若对Thread没有基本的了解,可以先阅读以下文章,同时部分的方法已经在如下两篇文章中介绍过了,本文不再重复介绍!! 【Java中Tread和Runnable创建新的线程的使用方法】 【Java中的Thread线程的七种属性的使用和分析】 提示:以下是本篇文章正文内容,下面案例可供参

    2024年02月15日
    浏览(11)
  • 详细分析Java中的list.foreach()和list.stream().foreach()

    详细分析Java中的list.foreach()和list.stream().foreach()

    典故来源于项目中使用了两种方式的foreach,后面尝试体验下有何区别! 先看代码示例: 使用List的forEach : 使用Stream API的forEach : 两者输出结果都为如下: 既然两个都输出差不多的结果,但两者还是稍微有些小区别,具体看下文! forEach() 是List接口的一部分,用于对列表中

    2024年04月25日
    浏览(10)
  • @DateTimeFormat注解

    @DateTimeFormat注解

    前言 前言在使用@DateTimeFormat进行格式化注解时,总是不能匹配前端传入的。格式总是报错 我这里使用的是pattern进行解析的的但是前端是给我传入的ISO类型的导致不能匹配所以总是报错。后来我们进行查看源码得到了答案。 源码解析 看下源码解析: 那么我们来看下。后端使

    2023年04月08日
    浏览(9)
  • 记一次DateTimeFormat注解的坑

    记一次DateTimeFormat注解的坑

    背景 :在用Echarts做图表时,前端传两个日期参数,获取日期区间的图表数据。想遵循RESTful风格,所以使用get请求获取date参数。前端读取当前日期,将七天前日期和当前日期作为参数传给后端,后端通过Date参数接收。然后后端报错,无法识别前端的date参数。经查阅,可以通

    2024年01月19日
    浏览(14)
  • Java中的注解,自定义注解

    Java中的注解,自定义注解

    框架 = 注解 + 反射 + 设计模式 注解( Annotation )是从JDK5.0开始引入,以“@注解名”在代码中存在。 Annotation 可以像修饰符一样被使用,可用于修饰包、类、构造器、方法、成员变量、参数、局部变量的声明。还可以添加一些参数值,这些信息被保存在 Annotation 的 “name=valu

    2023年04月16日
    浏览(9)
  • SpringBoot复习(30):@DateTimeFormat注解的使用

    一、实体类 二、控制器类:

    2024年02月13日
    浏览(11)
  • 详解Java中的注解

    在Java中,注解(Annotation)引入始于Java5,用来描述Java代码的元信息,通常情况下注解不会直接影响代码的执行,尽管有些注解可以用来做到影响代码执行。 Java中的注解通常扮演以下角色 编译器指令 构建时指令 运行时指令 其中 Java内置了三种编译器指令,本文后面部分会重点

    2024年03月10日
    浏览(28)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包