Java日期时间API系列26-----Jdk8中java.time包中的新的日期时间API类,YearMonth类的源码,转换和应用。
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类的源码,转换和应用。的更多相关文章
- 在swt中获取jar包中的文件 uri is not hierarchical
uri is not hierarchical 学习了:http://blog.csdn.net/zdsdiablo/article/details/1519719 在swt中获取jar包中的文件: ...
- Java基础进阶:时间类要点摘要,时间Date类实现格式化与解析源码实现详解,LocalDateTime时间类格式化与解析源码实现详解,Period,Duration获取时间间隔与源码实现,程序异常解析与处理方式
要点摘要 课堂笔记 日期相关 JDK7 日期类-Date 概述 表示一个时间点对象,这个时间点是以1970年1月1日为参考点; 作用 可以通过该类的对象,表示一个时间,并面向对象操作时间; 构造方法 ...
- Java基础系列--07_Object类的学习及源码分析
Object: 超类 (1)Object是类层次结构的顶层类,是所有类的根类,超类. 所有的类都直接或者间接的继承自Object类. 所有对象(包括数组)都实现这个类的方法 (2)Object ...
- API接口自动化之3 同一个war包中多个接口做自动化测试
同一个war包中多个接口做自动化测试 一个接口用一个测试类,每个测试用例如下,比如下面是4个测试用例,每个详细的测试用例中含有请求入参,返回体校验,以此来判断每条测试用例是否通过 一个war包中,若含 ...
- 7.Java集合-Arrays类实现原理及源码分析
Java集合---Arrays类源码解析 转自:http://www.cnblogs.com/ITtangtang/p/3948765.html 一.Arrays.sort()数组排序 Java A ...
- 🏆【Alibaba微服务技术系列】「Dubbo3.0技术专题」回顾Dubbo2.x的技术原理和功能实现及源码分析(温故而知新)
RPC服务 什么叫RPC? RPC[Remote Procedure Call]是指远程过程调用,是一种进程间通信方式,他是一种技术的思想,而不是规范.它允许程序调用另一个地址空间(通常是共享网络的另 ...
- arcgis api 3.x for js 地图加载多个 SHP 图层压缩以及 json 文件展示(附源码下载)
前言 关于本篇功能实现用到的 api 涉及类看不懂的,请参照 esri 官网的 arcgis api 3.x for js:esri 官网 api,里面详细的介绍 arcgis api 3.x 各个类 ...
- Andriod项目开发实战(1)——如何在Eclipse中的一个包下建新包
最开始是想将各个类分门别类地存放在不同的包中,所以想在项目源码包中新建几个不同功能的包eg:utils.model.receiver等,最后的结果应该是下图左边这样的: 很明显建立项目后的架构是上 ...
- java.util.Arrays类详解(源码总结)
概述 Arrays类位于java.util包下,是一个对数组操作的工具类.今天详细的看了看Arrays类的4千多行源码,现将Arrays类中的方法做一个总结(JDK版本:1.6.0_34).Array ...
- JDK中的Atomic包中的类及使用
引言 Java从JDK1.5开始提供了java.util.concurrent.atomic包,方便程序员在多线程环境下,无锁的进行原子操作.原子变量的底层使用了处理器提供的原子指令,但是不同的CPU ...
随机推荐
- P5665 [CSP-S2019] 划分
思路: 首先求出 \(a\) 的前缀和数组 \(s\). 考虑动态规划,令 \(dp_{i,j}\) 表示以 \(i\) 结尾,末尾有 \(j\) 个为一组的最小答案,则状态转移方程为: \[dp_{ ...
- 第九讲: MySQL为什么有时候会选错索引?
第九讲: MySQL为什么有时候会选错索引? 前面我们介绍过索引,你已经知道了在 MySQL 中一张表其实是可以支持多个索引的. 但是,你写 SQL 语句的时候,并没有主动指定使用哪个索引.也 ...
- 【Hadoop】3.3.1版本部署
硬件环境: 虚拟机环境配置 硬件:1CPU + [RAM]4G + [DISK]128G 系统:Centos7 x64 这里没有像尚硅谷一样做地址映射解析,直接取IP(我太懒) 192.168.242 ...
- 【Web】实现页面自动刷新的功能
技术发现自: https://www.bilibili.com/video/BV14v411b7JS?p=8 摘要自CSDN帖子: https://blog.csdn.net/senbar/artic ...
- 为什么要使用工业仿真软件? —— CAE(Computer Aided Engineering)工程设计中的计算机辅助工程
CAE技术: 引自: https://baike.baidu.com/item/CAE技术/18884456?fr=ge_ala 引自: https://www.mscsoftware.com.cn/ ...
- 中国2023年GDP增速5.2%
在中美贸易战和三年全球疫情的大背景下,我国的经济依旧保持强有力的增速,这表明了经济发展不断转好,一切恢复到疫情和贸易战之前也是有待期望的.
- 使用ChatGPT时的信息安全问题
ChatGPT由于其在对话方面的AI性能的卓越表现已经远远超越了同类的产品,因此赢得了国际科研领域的极大重视,并且也得到了广大用户的支持,但是在人们尽情使用的时候往往忘记了关于ChatGPT的信息安全 ...
- vant 爬坑 (一)
vant 通过脚手架安装: # 安装 Vue Cli npm install -g @vue/cli # 创建一个项目 vue create hello-world # 创建完成后,可以通过命令打开图 ...
- Cython将Numpy数组转为自定义结构体
技术背景 前面我们写过几篇关于Cython的文章,例如Cython计算谐振势.Cython与C语言的结合.Cython调用CUDA Kernel函数.Cython有着非常Pythonic的编程范式,又 ...
- C#应用 - 事件总线
目录 前言 1,简介 2,设计 2.1 设计思路 2.2 设计实现 2.2.1 IEventData 2.2.2 EventBus 2.2.3 用起来 3,问题 3.1 起缘 3.2 改造 3.3 用 ...