以下是 Java 8 中新日期时间 API 中常用的方法,用于处理日期和时间的创建、获取字段值、计算差异、格式化和解析等:
方法描述LocalDate.now()获取当前日期。LocalTime.now()获取当前时间。LocalDateTime.now()获取当前日期和时间。LocalDate.of(int year, int month, int day)创建指定日期。LocalTime.of(int hour, int minute)创建指定时间。LocalDateTime.of(int year, int month, int day, int hour, int minute)创建指定日期和时间。LocalDate.parse(CharSequence text)解析日期字符串。LocalTime.parse(CharSequence text)解析时间字符串。LocalDateTime.parse(CharSequence text)解析日期时间字符串。LocalDate.getYear()获取年份。LocalDate.getMonthValue()获取月份。LocalDate.getDayOfMonth()获取日期。LocalTime.getHour()获取小时。LocalTime.getMinute()获取分钟。LocalTime.getSecond()获取秒。LocalDateTime.plus(Duration amount)增加持续时间。LocalDateTime.minus(Duration amount)减少持续时间。Duration.between(Temporal startInclusive, Temporal endExclusive)计算两个时间点之间的时间差。Period.between(LocalDate startDateInclusive, LocalDate endDateExclusive)计算两个日期之间的时间差。DateTimeFormatter.ofPattern(String pattern)创建日期时间格式化器。Temporal.format(DateTimeFormatter formatter)格式化为字符串。TemporalAccessor.parse(CharSequence text, DateTimeFormatter formatter)解析字符串为日期或时间。ZoneId.of(String zoneId)创建时区。ZonedDateTime.now(ZoneId zone)获取带有时区的当前日期和时间。开发中的用到的两个注解
一般前端传递日期时间字符串,我们后端进行接收,就需要将日期时间字符串转成我们需要的 Date 类型的日期时间,即 String 到 Date 的转化
当我们从数据库中查出日期时间,是 Date 类型的日期时间,返回给前端就提供 JSON 数据,就需要讲 Date 类型的日期时间转成 字符串类型的日期时间,即 Date 到 String 的转化
有两个注解可以解决这两件事:Spring 提供的 @DateTimeFormat 和 Jackson 提供的 @JsonFormat
Jackson 相关依赖: