Date Time Java API Series 26 ----- Jdk8 new date and time API class java.time package, source code YearMonth class, conversion and applications.

Java8 added a class YearMonth to date, a card expiration date can be used and so on.

1.YearMonth

The default format is: 2007-12

Section 1.1 source code

*
 * @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;

As can be seen by the source code using the modified final YearMonth, YearMonth class is thread safe, while achieving Temporal, TemporalAdjuster, Comparable <YearMonth>, Serializable interface attributes have read, set and subtraction functions.

 

 

 1.2 to create and use a basic

        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);

Output:

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

 

2. Applications

2.1 Conversion

The Date turn YearMonth, YearMonth like transfer 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 staticToYearMonth YearMonth (the Instant Instant) { 
        the LocalDate localDate = toLocalDate (Instant);
         return YearMonth.of (localDate.getYear (), localDate.getMonthValue ()); 
    } 
    
    / ** 
     * ZonedDateTime turn YearMonth 
     * @param ZonedDateTime 
     * @return 
     * / 
    public  static YearMonth toYearMonth (ZonedDateTime ZonedDateTime) { 
        the localDate localDate = toLocalDate (ZonedDateTime);
         return YearMonth.of (localDate.getYear (), localDate.getMonthValue ()); 
    } 

    / ** 
     * YearMonth转Date
     * Note dayOfMonth range: between 1 to 31, The maximum value determination month special circumstances, such as the leap year February 29, non-leap years 28
     * If you want to convert to the last day of the month, the following methods may be used: toDateEndOfMonth (YearMonth) 
     * @param yearMonth 
     * @param the dayOfMonth 
     * @return 
     * / 
    public  static a Date toDate (YearMonth yearMonth, int the dayOfMonth) { 
        Objects.requireNonNull (yearMonth, " yearMonth " );
         return toDate (yearMonth.atDay (the dayOfMonth)); 
    } 
    
    / ** 
     * yearMonth turn Date, converting the first day of the month 
     * @param yearMonth 
     * @return 
     * / 
    public  staticToDateStartOfMonth DATE (YearMonth yearMonth) {
         return toDate (yearMonth,. 1 ); 
    } 
    
    / ** 
     * YearMonth turn Date, is converted to the last day of the month 
     * @param yearMonth 
     * @return 
     * / 
    public  static DATE toDateEndOfMonth (YearMonth yearMonth) { 
        Objects.requireNonNull (yearMonth, "yearMonth" );
         return toDate (yearMonth.atEndOfMonth ()); 
    } 

    / ** 
     * yearMonth turn the LocalDate 
     * Note dayOfMonth range: between 1 to 31, a maximum value is determined in accordance with special circumstances month, such as February 29 leap year , a non-leap year 28 
     * If you want to convert to the last day of the month, you can use the following method: toLocalDateEndOfMonth (YearMonth) 
     * @param yearMonth 
     * @paramthe dayOfMonth 
     * @return 
     * / 
    public  static the LocalDate toLocalDate (YearMonth yearMonth, int the dayOfMonth) { 
        Objects.requireNonNull (yearMonth, "yearMonth" );
         return yearMonth.atDay (the dayOfMonth); 
    } 
    
    / ** 
     * YearMonth turn LocalDate, conversion of the month one day 
     * @param yearMonth 
     * @return 
     * / 
    public  static the LocalDate toLocalDateStartOfMonth (yearMonth yearMonth) {
         return toLocalDate (yearMonth,. 1 );
    } 
    
    / ** 
     * yearMonth turn LocalDate, is converted to the last day of the month
     * @param yearMonth
     * @return
     */
    public static LocalDate toLocalDateEndOfMonth(YearMonth yearMonth) {
        Objects.requireNonNull(yearMonth, "yearMonth");
        return yearMonth.atEndOfMonth();
    }

 

Test code:

    @Test
     public  void yearMonthConverterTest () { 
        System.out.println ( "=================== yearMonthConverterTest =============== ====== " ); 
        a Date DATE = new new a Date (); 
        System.out.println (DATE); 
        yearMonth yearMonth = DateTimeConverterUtil.toYearMonth (DATE); 
        System.out.println (yearMonth); 
        
        a Date date1 = DateTimeConverterUtil. toDate (yearMonth, 15 );
         // convert first of the month 
        a Date DATE2 = DateTimeConverterUtil.toDateStartOfMonth (yearMonth);
         // convert the last day of the month 
        Date date3 =DateTimeConverterUtil.toDateEndOfMonth (yearMonth); 
        System.out.println (date1); 
        System.out.println (DATE2); 
        System.out.println (date3); 
        
        the LocalDate LocalDate1 = DateTimeConverterUtil.toLocalDate (yearMonth, 15 );
         // convert The first day of the month 
        the LocalDate LocalDate2 = DateTimeConverterUtil.toLocalDateStartOfMonth (yearMonth);
         // convert the last day of the month 
        the LocalDate LocalDate3 = DateTimeConverterUtil.toLocalDateEndOfMonth (yearMonth); 
        System.out.println (LocalDate1); 
        System.out.println (LocalDate2); 
        the System .out.println (LocalDate3); 
    }

 

Output:

===================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 computing

Get a list of dates in the middle of the start date, get a list of dates for a given month, whether or not expired, etc.

    /**
     * 获取指定区间的时间列表,包含起始
     * @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); 
    } 
    
    / ** 
     * Gets all the designated date list of dates 
     * @param yearMonth 
     * @return 
     * / 
    public  static List <the LocalDateTime> getLocalDateTimeList (yearMonth yearMonth) {
         return getLocalDateList (yearMonth) .stream () 
                .map (localDate -> DateTimeConverterUtil.toLocalDateTime (localDate)) the collect (Collectors.toList ());. 
    }     
    
    / ** 
     * date Gets a list of all the designated date 
     *@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){
        returngetLocalDateList (yearMonthStr) .stream () Map (localDate ->. DateTimeConverterUtil.toDate (localDate)) 
                .collect (Collectors.toList ()); 
    } 
    
    / ** 
     * is determined whether expired, (less than the current year, month, date input) 
     * @param yearMonth 
     * @return 
     * / 
    public  static  Boolean isExpiry (yearMonth yearMonth) { 
        Objects.requireNonNull (yearMonth, "yearMonth" );
         IF (yearMonth.isBefore (YearMonth.now ())) {
             return  to true ; 
        } 
        return  to false ; 
    } 
    
    / **
     * Determination has expired, (less than the current year, month, date input) 
     * @param yearMonthStr the MM-YYYY 
     * @return 
     * / 
    public  static  Boolean isExpiry (String yearMonthStr) { 
        Objects.requireNonNull (yearMonthStr, "yearMonthStr" ); 
        YearMonth yearMonth = YearMonth .parse (yearMonthStr);
         return isExpiry (yearMonth); 
    }

 

Test code:

    / ** 
     * yearMonth test 
     * / 
    @Test 
    public  void yearMonthTest () {
         // if expired 
        System.out.println (DateTimeCalculatorUtil.isExpiry ( "2020-03" )); 
        
        // Gets the specified date list of all dates 
        List < DATE> dateList = DateTimeCalculatorUtil.getDateList ( "2020-03" ); 
        dateList.stream () forEach (DATE. -> { 
            System.out.println (DateTimeFormatterUtil.formatToDateStr (DATE)); 
        }); 
        
        System.out.println ( "========================" ); 

        // get the list of designated time intervals, including an initial
        List<Date> dateList2 = DateTimeCalculatorUtil.getDateList(dateList.get(0), dateList.get(dateList.size()-1));
        dateList2.stream().forEach(date->{
            System.out.println(DateTimeFormatterUtil.formatToDateStr(date));
        });
        
    }

 

Output:

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

 

Source address: https://github.com/xkzhangsan/xk-time

 

Guess you like

Origin www.cnblogs.com/xkzhangsanx/p/12535828.html