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. 【MySQL】拆分经纬度字段

    数据结构: 表中一字段存储经度和纬度: +---------------------------+ | INSTALL_LOLA_NUM | +---------------------------+ ...

  2. 【Java】【常用类】String

    String表示字符串,Java所有的字符串字面值都是String类的实例实现 String是一个final修饰的类,代表不可变的字符序列 字符串是常量,用双引号表示,值在创建之后不能更改 Strin ...

  3. 【SpringBoot】01 快速上手

    环境搭建: JDK8 + IDEA 2018 + SpringBoot + Maven 3.0 + 创建Boot项目 2020.6.1更新补充: 最近才发现SpringBoot用IDEA构建项目会发生 ...

  4. 同策略强化学习算法可以使用经验缓存池(experience buffer)吗 ??? 设计一个基于缓存池的改进reinforce算法,给出初步的尝试 ---------- (reinforce + experience buffer)

    本文使用代码地址: https://gitee.com/devilmaycry812839668/reinforce_with_-experience-buffer ================= ...

  5. 强化学习:连续控制问题中Actor-Critic算法的linear baseline

    最近在看连续控制问题,看到了一个Actor-Critic算法中手动扩展features和设置linear baseline的方法,这些方法源自论文:<Benchmarking Deep Rein ...

  6. (持续更新)国内计算机领域相关的SCI和EI期刊,以及好中的SCI和EI期刊(不限国内外)

    好中的: SCI刊: EI刊: EI会议: 参考: CCF发布计算领域高质量科技期刊分级目录   国内的: SCI-Expanded   1. <Journal of Computer Scie ...

  7. CryptoHouse:由 ClickHouse 和 Goldsky 支持的免费区块链分析服务(ClickHouse 博客)

    我们很高兴地宣布 CryptoHouse,在 crypto.clickhouse.com 上可访问,这是一个由 ClickHouse 提供支持的免费区块链分析服务. https://crypto.cl ...

  8. 11-canvas绘制折线图

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

  9. RabbitMq高级特性之死信队列 通俗易懂 超详细 【内含案例】

    RabbitMq高级特性之死信队列 又称 死信交换机 DLX 介绍 当消息成为 Dead message 后,会重新发送到另一个交换机,这个交换机就是 DLX(死信交换机) 消息成为死信的情况公有三种 ...

  10. ZPL Viewer工具网站

    新上线的ZPL Viewer工具网站 大家好! 在工作中,我们经常需要设计和预览ZPL(Zebra Programming Language)文件.以前,我一直使用ZPL Design这类工具,但后来 ...