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. .NET 开源快捷的数据库文档查询和生成工具

    前言 在实际项目开发中,需求变更和项目迭代是常态.要求我们能够迅速响应,对数据库结构进行相应的调整,如添加新表.更新现有表结构或增加字段等. 为了确保团队成员之间的信息同步,实时更新和维护数据库文档变 ...

  2. 【RabbitMQ】04 路由模式

    在订阅模式的基础上制定一些特定发送规则 创建路由模式的生产者: 注意这些变化,跟之前的订阅模式并不一样 package cn.dzz.routineQueueInProducer; import co ...

  3. 很好用的python游戏环境(续2):强化学习算法走迷宫游戏环境(导航问题 navigation):分享一个python语言的迷宫游戏环境

    相关前文: 很好用的python游戏环境(续):强化学习算法走迷宫游戏环境(导航问题 navigation):分享一个python语言的迷宫游戏环境 项目的GitHub地址: https://gith ...

  4. 在docker容器中创建用户组和用户,并且多用户共用一个anaconda环境

    背景: 实验室可以使用一个浪潮的AI计算平台,该平台运行的都是docker容器,并且不能联网,因此谁要是想要安装什么软件的话就需要自己单独打包镜像到平台上,大致步骤为: 1.   在平台的镜像管理中找 ...

  5. 【转载】 机器学习的高维数据可视化技术(t-SNE 介绍) 外文博客原文:How t-SNE works and Dimensionality Reduction

    原文地址: https://www.displayr.com/using-t-sne-to-visualize-data-before-prediction/ 该文是网上传的比较多的一个 t-SNE ...

  6. 3.2.0 版本预告!远程日志解决 Worker 故障获取不到日志的问题

    Apache DolphinScheduler 3.2.0 版本已经呼之欲出,8 月 中下旬,这个大版本就要和用户见面了.为了让大家提前了解到此版本更新的主要内容,我们已经制作了几期视频和内容做了大致 ...

  7. 07-canvas绘制虚线

    1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="U ...

  8. 记录_玩客云v1.0大坑!!!

    刷机 短接后刷入uboot固件, 制作U盘镜像启动会出现莫名其妙的内存写入失败!!!!!!!!!!! 但是这并没坏 拆机 , 短接刷armbian v5.67  内核 3.10, 这个版本刷完后什么特 ...

  9. iPhone 打不开 Apple News 解决方法

    想看 Apple News,但是在主屏幕找不到,在 App Store 搜索 Apple News 后打开时显示访问控制已启用,然而在设置中检查发现访问控制并没有启用. 经过一番摸索,发现这个访问控制 ...

  10. 【图文安装教程】在docker中安装kibana

    在上一篇中,我们已经在docker里面安装了ES. kibana可以给我们提供一个elasticsearch的可视化界面,便于我们学习. 所以,本篇咱们就在docker里面安装kibana图文教程: ...