Java YearMonth日期类应用

Java YearMonth日期类应用

在项目中会遇到仅需要存取年月,由于数据库一般不支持不完整日期格式,因此日期之间转换比较麻烦。本文通过介绍YearMonth类实现年月日期存取过程。

1. 概述

YearMonth是不可变的日期时间对象,表示年、月的组合。其实现了Comparable接口。

2. YearMonth类方法

YearMonth类主要方法如下表:

方法 描述
String format(DateTimeFormatter formatter) 使用特定的格式格式化year-month
int get(TemporalField field) 返回日期中特定域的int类型
boolean isLeapYear() 是否闰年
static YearMonth now() 根据当前时间返回YearMonth实例
static YearMonth of(int year, int month) 根据年、月返回YearMonth实例
YearMonth plus(TemporalAmount amountToAdd) 返回year-month增加一定数量的拷贝
YearMonth minus (TemporalAmount amountToSubtract) 返回year-month减少一定数量的拷贝

3. YearMonth类方法示例

格式化为字符串

YearMonth ym = YearMonth.now();  
String s = ym.format(DateTimeFormatter.ofPattern("MM yyyy"));  
System.out.println(s);  

获取特定域

YearMonth y = YearMonth.now();  
long l1 = y.get(ChronoField.YEAR);  
System.out.println(l1);  
long l2 = y.get(ChronoField.MONTH_OF_YEAR);  
System.out.println(l2);  

增加月份

YearMonth ym1 = YearMonth.now();  
YearMonth ym2 = ym1.plus(Period.ofYears(2));  
System.out.println(ym2);  

减少月份

YearMonth ym1 = YearMonth.now();  
YearMonth ym2 = ym1.minus(Period.ofYears(2));  
System.out.println(ym2);  

4.实际应用

实际项目需求中每月需要制定计划,计划月份无需精确到日,所有打算使用YearMonth类型。但数据库层不支持YearMonth,只能存储Date类型,需要必要的转换。

4.1. 定义前端请求实体

static final String STD_YEAR_MONTH_PATTERN = "yyyy-MM"

@JsonFormat(pattern = STD_YEAR_MONTH_PATTERN, shape = JsonFormat.Shape.STRING)
@DateTimeFormat(pattern = STD_YEAR_MONTH_PATTERN)
YearMonth planMonth;

4.2 定义实体类型

因为实体类型对应数据库,故定义为LocalDate类型。

private LocalDate planMonth;

4.3. 类型转换

/**
    * 转换YearMonth为LocalDate
    */
public static LocalDate parseDateYearMonth(YearMonth yearMonth){
    return LocalDate.of(yearMonth.getYear(),yearMonth.getMonthValue(),1);
}

/**
    * 转换LocalDate为YearMonth
    */
public static YearMonth parseYearMonth(LocalDate localDate){
    return YearMonth.of(localDate.getYear(),localDate.getMonthValue());
}

自动映射

实际中DTO之间映射通过Orika 框架实现,但REQ类与实体类之间的日期类型不统一,需要手工通过上述方法进行映射,所以需要忽略该字段进行映射。定义映射规则如下:

@Component
public class DtoMapper extends ConfigurableMapper {

@Override
protected void configure(MapperFactory factory) {
    factory.classMap(ZfjgPlanEntity.class,ZfjgPlanReq.class)
        .exclude("planMonth")
        .byDefault().register();
}

}

总结

本文介绍了YearMonth类及其主要方法。同时也介绍实际项目中如何进行转换和存储。

猜你喜欢

转载自blog.csdn.net/neweastsun/article/details/81702426