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. 免费正版 IntelliJ IDEA license 详细指南

    一.前言 IntelliJ IDEA 一直是我非常喜欢的 IDE 自从用上之后就回不了头了,但是 Ultimate 版本的费用十分昂贵,其实 JetBrains 自己就提供了6种免费申请授权的方式:本 ...

  2. Spring AOP概念及原理

    Spring AOP(面向切面编程) 以下内容由ChatGPT生成 AOP(Aspect-Oriented Programming,面向切面编程)是一种编程范式,旨在通过分离关注点来提高程序的模块化. ...

  3. 【SpringBoot】11 Web开发 Part2 模板引擎

    开发回顾: JavaWeb开发使用JSP技术,所有的页面文件必须是JSP,才能接受数据处理 JSP的好处是,数据交互方便,有JSTL补充 SpringBoot的区别: 我们最终的项目是一个jar包 内 ...

  4. 树莓派3b+使用官方屏幕后倒置问题——屏幕倒置

    树莓派3b+的屏幕本身就是倒置的,因此为了使树莓派在官方屏幕下能显示正常的屏幕画面因此需要通过设置把树莓派的官方屏幕的输出倒置一下,这样树莓派的官方屏幕的输出就是正常的了. 解决方法:(源自:http ...

  5. UBUNTU18.04 SERVER 多显卡 服务器,为防止显卡计算任务出现不意外报错,设置显卡工作状态为:设定持久模式

    参考: https://www.cnblogs.com/devilmaycry812839668/p/14799016.html https://www.cnblogs.com/devilmaycry ...

  6. MindSpore 初探, 使用LeNet训练minist数据集

    如题所述,官网地址: https://www.mindspore.cn/tutorial/zh-CN/r1.2/quick_start.html 数据集下载: mkdir -p ./datasets/ ...

  7. 从hp的暗影精灵4来看移动cpu的实际性能表现与官方出厂性能数据之间的差距

    手上有一款暗影精灵4的笔记本,CPU为i7-9750H,官方给出的睿频为4.5Ghz,但是自己使用过程中最高睿频只能达到3.9Ghz与4.1Ghz之间,根本就没有超过4.1Ghz的时候. (图的原网址 ...

  8. 在一串字符串中Java使用正则匹配电话号码的方法

    1.使用正则表达式来匹配电话号码 在Java中,使用正则表达式匹配电话号码是一个常见的需求.电话号码的格式可能因国家/地区而异,但一个典型的格式可能是这样的:(123) 456-7890.在这个例子中 ...

  9. DIjkstra进阶模板 路径记录 按权重(结点数最小等)记录

    struct DIJ { using i64 = long long; using PII = pair<i64, i64>; vector<i64> dis, path, n ...

  10. Mac升级Ventura 13.0.1后无法远程ssh连接服务器

    原因 原因是Mac os Ventura升级了ssh到9.0,ssl到3.3.6,而服务器上的sshd还是老版本:服务器上的老版本ssh和ssl无法和mac上的新版本ssh和ssl交互,新版本ssh加 ...