jdk8 新特性 local日期其他类

118 阅读2分钟

「这是我参与11月更文挑战的第8天,活动详情查看:2021最后一次更文挑战

with指定

指定属性

  • withYear
  • withMonth
  • withDay
  • withHour
  • withMinute
  • withSecond

将指定的属性替换成参数,其他属性复制过来,返回行的对象.

替换的参数会进行校验,如果不符合条件就会抛出异常

LocalDate parse = LocalDate.parse("2021-08-09");
// 将month 属性替换成3,其他属性不变,创建一个新的对象localDate3
LocalDate localDate3 = parse.withMonth(3);    // 2021-03-09

// 对参数进行校验
public boolean isValidValue(long value) {
        return (value >= getMinimum() && value <= getMaximum());
    }

通过时间调整器创建

with(*TemporalAdjuster* adjuster)

  • firstDayOfMonth
  • lastDayOfMonth
  • firstDayOfNextMonth
  • firstDayOfYear
  • lastDayOfYear
  • firstDayOfNextYear
  • firstInMonth
  • lastInMonth
  • dayOfWeekInMonth(int ordinal, DayOfWeek dayOfWeek) : 这个月第几个星期几是几号
  • next(DayOfWeek dayOfWeek): 下个星期几
  • nextOrSame
  • previous
  • previousOrSame
// parse : 2021-08-09   
// 这个月初
LocalDate with = parse.with(TemporalAdjusters.firstDayOfMonth());  // 2021-08-01
// 下一年初
LocalDate with1 = parse.with(TemporalAdjusters.firstDayOfNextYear());  // 2022-01-01

MONTH

MONTH是个枚举类,有十二个枚举属性,分别是十二个月份.

		public enum Month implements TemporalAccessor, TemporalAdjuster {
		JANUARY,
    FEBRUARY,
    MARCH,
    APRIL,
		....
// 该数组用于存储上述的常量.
private static final Month[] ENUMS = Month.values();

image.png

Month对象NOVEMEBER 对应的应该是11月份,而ordinal是10;

MONTH中存储这一个数组,将月份存储到数组中.因此从0开始.

增加月份

Month对象增加月份

plus增加月份,minus减少月份

				Month month = date.getMonth();   // NOVEMBER
				// 增加3月份
				Month plus = month.plus(2);    // JANUARY
        // 获取月份
        int value = plus.getValue();   // 1

获取月份日期

11 月的有30天,2月只有28天

				Month month = date.getMonth();    // NOVEMBER
        int i1 = month.minLength();    //30
        Month plus = month.plus(3);     // FEBRUARY
        int i2 = plus.minLength();     //28

Period

用于计算日期间隔

between(LocalDate date1,LocalDate date2)

Period between = Period.between(parse, localDate3);// 2021-08-09  //2021-08-01  
// -8D 代表-8day

// 2021-08-09         // 2022-03-03
Period between = Period.between(parse, localDate3.withDayOfMonth(3))
// -5M-6D   小5个月又6天

查看源码,发现他的属性也是final修饰的年月日.

private final int years;   
private final int months;
private final int days;

因此有三个get方法获取属性

  • getYears()
  • getMonths()
  • getDays()

of方法创造Period对象.由于是日期间隔,因此不校验是否符合日期规范

  • ofYears(int years): 指定year,其他默认为0
  • ofMonths(int months) : 指定month,其他默认为0
  • ofWeeks(int weeks) : 指定周数,日期 = week * 7
  • ofDays()
  • of()
Period period = Period.ofYears(11);  // 11Y

Period period1 = Period.ofWeeks(5);    // 35D

Period of4 = Period.of(33, 33, 33);  // 33Y33M33D