Java8中为年月新增了类YearMonth,可以用来表示卡片过期时间等问题。

1.YearMonth

默认格式为:2007-12

1.1 部分源码

*
* @implSpec
* This class is immutable and thread-safe.
*
* @since 1.8
*/
public final class YearMonth
implements Temporal, TemporalAdjuster, Comparable<YearMonth>, Serializable { /**
* Serialization version.
*/
private static final long serialVersionUID = 4183400860270640070L;
/**
* Parser.
*/
private static final DateTimeFormatter PARSER = new DateTimeFormatterBuilder()
.appendValue(YEAR, 4, 10, SignStyle.EXCEEDS_PAD)
.appendLiteral('-')
.appendValue(MONTH_OF_YEAR, 2)
.toFormatter(); /**
* The year.
*/
private final int year;
/**
* The month-of-year, not null.
*/
private final int month;

通过源码可以看出使用final修饰YearMonth,YearMonth是线程安全类,同时实现了Temporal, TemporalAdjuster, Comparable<YearMonth>, Serializable接口,有属性读取,设置和加减等功能。

1.2 创建和基本使用

        YearMonth yearMonth = YearMonth.now();
YearMonth yearMonth2 = YearMonth.of(2020, 4); System.out.println(yearMonth);
System.out.println(yearMonth2);
YearMonth yearMonth3 = YearMonth.parse("2020-05");
System.out.println(yearMonth3); YearMonth yearMonth4 = yearMonth3.plusMonths(1);
System.out.println(yearMonth4);

输出:

2020-03
2020-04
2020-05
2020-06

2.应用

2.1 转换

如Date转YearMonth,YearMonth转Date等
    /**
* Date转YearMonth
* @param date
* @return
*/
public static YearMonth toYearMonth(Date date){
LocalDate localDate = toLocalDate(date);
return YearMonth.of(localDate.getYear(), localDate.getMonthValue());
} /**
* LocalDateTime转YearMonth
* @param localDateTime
* @return
*/
public static YearMonth toYearMonth(LocalDateTime localDateTime){
LocalDate localDate = toLocalDate(localDateTime);
return YearMonth.of(localDate.getYear(), localDate.getMonthValue());
} /**
* LocalDate转YearMonth
* @param localDate
* @return
*/
public static YearMonth toYearMonth(LocalDate localDate){
Objects.requireNonNull(localDate, "localDate");
return YearMonth.of(localDate.getYear(), localDate.getMonthValue());
} /**
* Instant转YearMonth
* @param instant
* @return
*/
public static YearMonth toYearMonth(Instant instant){
LocalDate localDate = toLocalDate(instant);
return YearMonth.of(localDate.getYear(), localDate.getMonthValue());
} /**
* ZonedDateTime转YearMonth
* @param zonedDateTime
* @return
*/
public static YearMonth toYearMonth(ZonedDateTime zonedDateTime){
LocalDate localDate = toLocalDate(zonedDateTime);
return YearMonth.of(localDate.getYear(), localDate.getMonthValue());
} /**
* YearMonth转Date
* 注意dayOfMonth范围:1到31之间,最大值根据月份确定特殊情况,如2月闰年29,非闰年28
* 如果要转换为当月最后一天,可以使用下面方法:toDateEndOfMonth(YearMonth)
* @param yearMonth
* @param dayOfMonth
* @return
*/
public static Date toDate(YearMonth yearMonth, int dayOfMonth) {
Objects.requireNonNull(yearMonth, "yearMonth");
return toDate(yearMonth.atDay(dayOfMonth));
} /**
* YearMonth转Date,转换为当月第一天
* @param yearMonth
* @return
*/
public static Date toDateStartOfMonth(YearMonth yearMonth) {
return toDate(yearMonth, 1);
} /**
* YearMonth转Date,转换为当月最后一天
* @param yearMonth
* @return
*/
public static Date toDateEndOfMonth(YearMonth yearMonth) {
Objects.requireNonNull(yearMonth, "yearMonth");
return toDate(yearMonth.atEndOfMonth());
} /**
* YearMonth转LocalDate
* 注意dayOfMonth范围:1到31之间,最大值根据月份确定特殊情况,如2月闰年29,非闰年28
* 如果要转换为当月最后一天,可以使用下面方法:toLocalDateEndOfMonth(YearMonth)
* @param yearMonth
* @param dayOfMonth
* @return
*/
public static LocalDate toLocalDate(YearMonth yearMonth, int dayOfMonth) {
Objects.requireNonNull(yearMonth, "yearMonth");
return yearMonth.atDay(dayOfMonth);
} /**
* YearMonth转LocalDate,转换为当月第一天
* @param yearMonth
* @return
*/
public static LocalDate toLocalDateStartOfMonth(YearMonth yearMonth) {
return toLocalDate(yearMonth, 1);
} /**
* YearMonth转LocalDate,转换为当月最后一天
* @param yearMonth
* @return
*/
public static LocalDate toLocalDateEndOfMonth(YearMonth yearMonth) {
Objects.requireNonNull(yearMonth, "yearMonth");
return yearMonth.atEndOfMonth();
}

测试代码:

    @Test
public void yearMonthConverterTest(){
System.out.println("===================yearMonthConverterTest=====================");
Date date = new Date();
System.out.println(date);
YearMonth yearMonth = DateTimeConverterUtil.toYearMonth(date);
System.out.println(yearMonth); Date date1 = DateTimeConverterUtil.toDate(yearMonth, 15);
//转换为当月第一天
Date date2 = DateTimeConverterUtil.toDateStartOfMonth(yearMonth);
//转换为当月最后一天
Date date3 = DateTimeConverterUtil.toDateEndOfMonth(yearMonth);
System.out.println(date1);
System.out.println(date2);
System.out.println(date3); LocalDate LocalDate1 = DateTimeConverterUtil.toLocalDate(yearMonth, 15);
//转换为当月第一天
LocalDate LocalDate2 = DateTimeConverterUtil.toLocalDateStartOfMonth(yearMonth);
//转换为当月最后一天
LocalDate LocalDate3 = DateTimeConverterUtil.toLocalDateEndOfMonth(yearMonth);
System.out.println(LocalDate1);
System.out.println(LocalDate2);
System.out.println(LocalDate3);
}

输出:

===================yearMonthConverterTest=====================
Fri Mar 20 23:41:41 CST 2020
2020-03
Sun Mar 15 00:00:00 CST 2020
Sun Mar 01 00:00:00 CST 2020
Tue Mar 31 00:00:00 CST 2020
2020-03-15
2020-03-01
2020-03-31

2.2 计算

获取起始日期中间的日期列表,获取指定月份的日期列表,判断是否过期等等

    /**
* 获取指定区间的时间列表,包含起始
* @param startInclusive
* @param endInclusive
* @return
*/
public static List<LocalDateTime> getLocalDateTimeList(LocalDateTime startInclusive, LocalDateTime endInclusive){
Objects.requireNonNull(startInclusive, "startInclusive");
Objects.requireNonNull(endInclusive, "endInclusive");
if(startInclusive.isAfter(endInclusive)){
throw new DateTimeException("startInclusive must before or equal endInclusive!");
}
List<LocalDateTime> localDateTimeList = new ArrayList<LocalDateTime>();
long days = betweenTotalDays(startInclusive, endInclusive)+1;
for(long i=0; i<days; i++){
localDateTimeList.add(startInclusive.plusDays(i));
}
return localDateTimeList;
} /**
* 获取指定区间的时间列表,包含起始
* @param startInclusive
* @param endInclusive
* @return
*/
public static List<LocalDate> getLocalDateList(LocalDate startInclusive, LocalDate endInclusive){
return getLocalDateTimeList(DateTimeConverterUtil.toLocalDateTime(startInclusive),
DateTimeConverterUtil.toLocalDateTime(endInclusive)).stream()
.map(localDateTime -> localDateTime.toLocalDate()).collect(Collectors.toList());
} /**
* 获取指定区间的时间列表,包含起始
* @param startInclusive
* @param endInclusive
* @return
*/
public static List<Date> getDateList(Date startInclusive, Date endInclusive){
return getLocalDateTimeList(DateTimeConverterUtil.toLocalDateTime(startInclusive),
DateTimeConverterUtil.toLocalDateTime(endInclusive)).stream()
.map(localDateTime -> DateTimeConverterUtil.toDate(localDateTime)).collect(Collectors.toList());
} /**
* 获取指定年月的所有日期列表
* @param YearMonth
* @return
*/
public static List<LocalDate> getLocalDateList(YearMonth yearMonth){
Objects.requireNonNull(yearMonth, "yearMonth");
List<LocalDate> localDateList = new ArrayList<LocalDate>();
long days = yearMonth.lengthOfMonth();
LocalDate localDate = DateTimeConverterUtil.toLocalDateStartOfMonth(yearMonth);
for(long i=0; i<days; i++){
localDateList.add(plusDays(localDate, i));
}
return localDateList;
} /**
* 获取指定年月的所有日期列表
* @param yearMonthStr yyyy-MM
* @return
*/
public static List<LocalDate> getLocalDateList(String yearMonthStr){
Objects.requireNonNull(yearMonthStr, "yearMonthStr");
YearMonth yearMonth = YearMonth.parse(yearMonthStr);
return getLocalDateList(yearMonth);
} /**
* 获取指定年月的所有日期列表
* @param yearMonth
* @return
*/
public static List<LocalDateTime> getLocalDateTimeList(YearMonth yearMonth){
return getLocalDateList(yearMonth).stream()
.map(localDate -> DateTimeConverterUtil.toLocalDateTime(localDate)).collect(Collectors.toList());
} /**
* 获取指定年月的所有日期列表
* @param yearMonthStr yyyy-MM
* @return
*/
public static List<LocalDateTime> getLocalDateTimeList(String yearMonthStr){
return getLocalDateList(yearMonthStr).stream()
.map(localDate -> DateTimeConverterUtil.toLocalDateTime(localDate)).collect(Collectors.toList());
} /**
* 获取指定年月的所有日期列表
* @param yearMonthStr yyyy-MM
* @return
*/
public static List<Date> getDateList(String yearMonthStr){
return getLocalDateList(yearMonthStr).stream().map(localDate -> DateTimeConverterUtil.toDate(localDate))
.collect(Collectors.toList());
} /**
* 判断是否过期,(输入年月小于当前年月)
* @param yearMonth
* @return
*/
public static boolean isExpiry(YearMonth yearMonth){
Objects.requireNonNull(yearMonth, "yearMonth");
if(yearMonth.isBefore(YearMonth.now())){
return true;
}
return false;
} /**
* 判断是否过期,(输入年月小于当前年月)
* @param yearMonthStr yyyy-MM
* @return
*/
public static boolean isExpiry(String yearMonthStr){
Objects.requireNonNull(yearMonthStr, "yearMonthStr");
YearMonth yearMonth = YearMonth.parse(yearMonthStr);
return isExpiry(yearMonth);
}

测试代码:

    /**
* yearMonth测试
*/
@Test
public void yearMonthTest(){
//是否过期
System.out.println(DateTimeCalculatorUtil.isExpiry("2020-03")); //获取指定年月的所有日期列表
List<Date> dateList = DateTimeCalculatorUtil.getDateList("2020-03");
dateList.stream().forEach(date->{
System.out.println(DateTimeFormatterUtil.formatToDateStr(date));
}); System.out.println("========================"); //获取指定区间的时间列表,包含起始
List<Date> dateList2 = DateTimeCalculatorUtil.getDateList(dateList.get(0), dateList.get(dateList.size()-1));
dateList2.stream().forEach(date->{
System.out.println(DateTimeFormatterUtil.formatToDateStr(date));
}); }

输出:

false
2020-03-01
2020-03-02
2020-03-03
2020-03-04
2020-03-05
2020-03-06
2020-03-07
2020-03-08
2020-03-09
2020-03-10
2020-03-11
2020-03-12
2020-03-13
2020-03-14
2020-03-15
2020-03-16
2020-03-17
2020-03-18
2020-03-19
2020-03-20
2020-03-21
2020-03-22
2020-03-23
2020-03-24
2020-03-25
2020-03-26
2020-03-27
2020-03-28
2020-03-29
2020-03-30
2020-03-31
========================
2020-03-01
2020-03-02
2020-03-03
2020-03-04
2020-03-05
2020-03-06
2020-03-07
2020-03-08
2020-03-09
2020-03-10
2020-03-11
2020-03-12
2020-03-13
2020-03-14
2020-03-15
2020-03-16
2020-03-17
2020-03-18
2020-03-19
2020-03-20
2020-03-21
2020-03-22
2020-03-23
2020-03-24
2020-03-25
2020-03-26
2020-03-27
2020-03-28
2020-03-29
2020-03-30
2020-03-31

源代码地址:https://github.com/xkzhangsan/xk-time

Java日期时间API系列26-----Jdk8中java.time包中的新的日期时间API类,YearMonth类的源码,转换和应用。的更多相关文章

  1. 在swt中获取jar包中的文件 uri is not hierarchical

    uri is not hierarchical 学习了:http://blog.csdn.net/zdsdiablo/article/details/1519719 在swt中获取jar包中的文件: ...

  2. Java基础进阶:时间类要点摘要,时间Date类实现格式化与解析源码实现详解,LocalDateTime时间类格式化与解析源码实现详解,Period,Duration获取时间间隔与源码实现,程序异常解析与处理方式

    要点摘要 课堂笔记 日期相关 JDK7 日期类-Date 概述 表示一个时间点对象,这个时间点是以1970年1月1日为参考点; 作用 可以通过该类的对象,表示一个时间,并面向对象操作时间; 构造方法 ...

  3. Java基础系列--07_Object类的学习及源码分析

    Object: 超类 (1)Object是类层次结构的顶层类,是所有类的根类,超类.   所有的类都直接或者间接的继承自Object类.   所有对象(包括数组)都实现这个类的方法 (2)Object ...

  4. API接口自动化之3 同一个war包中多个接口做自动化测试

    同一个war包中多个接口做自动化测试 一个接口用一个测试类,每个测试用例如下,比如下面是4个测试用例,每个详细的测试用例中含有请求入参,返回体校验,以此来判断每条测试用例是否通过 一个war包中,若含 ...

  5. 7.Java集合-Arrays类实现原理及源码分析

    Java集合---Arrays类源码解析  转自:http://www.cnblogs.com/ITtangtang/p/3948765.html 一.Arrays.sort()数组排序 Java A ...

  6. 🏆【Alibaba微服务技术系列】「Dubbo3.0技术专题」回顾Dubbo2.x的技术原理和功能实现及源码分析(温故而知新)

    RPC服务 什么叫RPC? RPC[Remote Procedure Call]是指远程过程调用,是一种进程间通信方式,他是一种技术的思想,而不是规范.它允许程序调用另一个地址空间(通常是共享网络的另 ...

  7. arcgis api 3.x for js 地图加载多个 SHP 图层压缩以及 json 文件展示(附源码下载)

    前言 关于本篇功能实现用到的 api 涉及类看不懂的,请参照 esri 官网的 arcgis api 3.x for js:esri 官网 api,里面详细的介绍 arcgis api 3.x 各个类 ...

  8. Andriod项目开发实战(1)——如何在Eclipse中的一个包下建新包

    最开始是想将各个类分门别类地存放在不同的包中,所以想在项目源码包中新建几个不同功能的包eg:utils.model.receiver等,最后的结果应该是下图左边这样的:   很明显建立项目后的架构是上 ...

  9. java.util.Arrays类详解(源码总结)

    概述 Arrays类位于java.util包下,是一个对数组操作的工具类.今天详细的看了看Arrays类的4千多行源码,现将Arrays类中的方法做一个总结(JDK版本:1.6.0_34).Array ...

  10. JDK中的Atomic包中的类及使用

    引言 Java从JDK1.5开始提供了java.util.concurrent.atomic包,方便程序员在多线程环境下,无锁的进行原子操作.原子变量的底层使用了处理器提供的原子指令,但是不同的CPU ...

随机推荐

  1. (六)Redis 消息队列 List、Streams

    Redis 适合做消息队列吗?有什么解决方案?首先要明白消息队列的消息存取需求和工作流程. 1.消息队列 我们一般把消息队列中发送消息的组件称为生产者,把接收消息的组件称为消费者,下图是一个通用的消息 ...

  2. 使用ventoy安装windows10

    使用ventoy安装windows10 在ventoy中选择windows10镜像 进入Windows安装界面 下一步,选择现在安装 稍等片刻 选择我没有产品密钥 根据需求选择对应版本 下一步,接受许 ...

  3. docker dockerfile基础指令

    dockerfile是用来构建docker镜像文件!命令参数脚本 构建步骤 1.编写一个dockerfile文件 2.dockerbuild构建成为一个镜像 3.docker run运行镜像 4.do ...

  4. ByteHouse高性能向量检索实践——“以图搜图”

    更多技术交流.求职机会,欢迎关注字节跳动数据平台微信公众号,回复[1]进入官方交流群   随着 LLM 技术的发展,向量检索与向量数据库也受到业界持续关注,它们能够为LLM提供外置记忆单元,通过提供与 ...

  5. 【H5】05 高阶文字排版

    摘自: https://developer.mozilla.org/zh-CN/docs/Learn/HTML/Introduction_to_HTML/Advanced_text_formattin ...

  6. 【RabbitMQ】03 订阅模式

    Pub / Sub 订阅模式 特点是 一条消息可以给多个消费者接收了 首先创建订阅模式生产者发生一些代码变动: package cn.dzz.pubSub; import com.rabbitmq.c ...

  7. 【Vue】接口模块化处理

    在前端Vue项目中,接口会被统一放在一个目录中管理: 一个模块的所有接口放在一个JS文件中: 文件会导入封装好的请求方法,和动态绑定的接口地址 import request from '@/utils ...

  8. 【IDEA】使用Maven骨架创建JavaWeb项目

    IDEA版本:2020.1 骨架选项名称: org.apache.maven.archetypes:maven-archetype-webapp 本项目的Maven坐标设置: 设置优先从本地获取骨架: ...

  9. 论文写作:写回复意见时的套话 (reviews and comments)

    Typos, Grammar, and Citation Errors: We acknowledge the need for a thorough proofreading to rectify ...

  10. Python多进程共享numpy 数组

    引用:https://zhuanlan.zhihu.com/p/32513483 共享 numpy 数组 需要用到 numpy 时往往是数据量较大的场景,如果直接复制会造成大量内存浪费.共享 nump ...