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类及其主要方法。同时也介绍实际项目中如何进行转换和存储。

  • 4
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值