Java 8 – Period

Java 8 – Period

原文: https://howtodoinjava.com/java/date-time/java8-period/

ISO-8601 日历系统中,使用 Java 8 Period类,在基于日期的值(例如天,月,年,周或年)中学习查找两个日期之间的差异

1. Period

Period类用于使用 ISO-8601 时间段格式PnYnMnDPnW中基于日期的值来表示时间量。 例如,P20Y2M25D字符串代表 20 年,2 个月和 25 天。

此时间段可以通过不同方式获得。

1.1 Period.between()

通常,Period用于表示两个日期之间的时间段(例如,两个LocalDate实例之间的时间段)。

LocalDate startLocalDate = LocalDate.of(2020, 3, 12);
LocalDate endLocalDate = LocalDate.of(2020, 7, 20);

Period periodBetween = Period.between(startLocalDate, endLocalDate);
System.out.println(periodBetween);	// P4M8D - 4 months and 8 days

System.out.println(periodBetween.getDays());		//8
System.out.println(periodBetween.getMonths());		//4
System.out.println(periodBetween.getYears());		//0

System.out.println(periodBetween.get(ChronoUnit.DAYS));	//8

1.2 Period.ofDays()

Period分类以下方法,以不同单位表示时间段:

  • ofDays(int days) – 表示天数的时间段。
  • ofMonths(int months) – 表示月数的时间段。
  • ofWeeks(int weeks) – 表示周数的时间段。
  • ofYears(int years) – 表示年数的时间段。
Period fromDays = Period.ofDays(150);	// 150 days
Period fromMonths = Period.ofMonths(4);	// 4 months
Period fromYears = Period.ofYears(10);	// 10 years
Period fromWeeks = Period.ofWeeks(15);	// 15 weeks

1.3 Period.of()

使用of(int years, int months, int days),我们可以获得基于年,月和日的实例。

//20 years, 3 months and 20 days
Period periodFromUnits = Period.of(20, 3, 20);

1.4 Period.parse()

可以从包含 ISO-8601 时间段格式的String中获得Period

//20 years, 3 months and 20 days
Period periodFromString1 = Period.parse("P20Y3M20D");

//365 Days
Period periodFromString2 = Period.parse("P365D");

//52 Weeks
Period periodFromString3 = Period.parse("P52W");

2. 获取Period

时间段值可以通过获取器方法获得:

  • Period.getDays() - 获取此时间段的天数。
  • Period.getMonths() - 获取此时间段的月数。
  • Period.getYears() - 获取此时间段的年数。
  • Period.get(TemporalUnit unit) - 获取所请求单位的值。 请注意,支持的单位是YEARS, MONTHS, DAYS。 所有其他单元都抛出UnsupportedTemporalTypeException
LocalDate startLocalDate = LocalDate.of(2020, 3, 12);
LocalDate endLocalDate = LocalDate.of(2020, 7, 20);

Period periodBetween = Period.between(startLocalDate, endLocalDate);

System.out.println(periodBetween.getDays());		//8
System.out.println(periodBetween.getMonths());		//4
System.out.println(periodBetween.getYears());		//0

System.out.println(periodBetween.get(ChronoUnit.DAYS));	//8

//Throws UnsupportedTemporalTypeException
System.out.println(periodBetween.get(ChronoUnit.WEEKS));	

3. 修改Period

我们可以从给定的Period对象中添加或减去一段时间。 支持加减法的方法有:

  • add(Period) – 返回给定时间段的副本,其中添加了指定的时间段。
  • plusYears() – 返回给定时间段的副本,其中添加了指定的年份。
  • plusMonths() – 返回给定时间段的副本,其中添加了指定的月份。
  • plusDays() – 返回给定时间段的副本,其中添加了指定的日期。
  • minus(period)-返回给定时间段的副本,减去指定时间段。
  • minusYears()-返回给定时间段的副本,其中减去指定的年份。
  • minusMonths() – 返回给定时间段的副本,其中减去指定的月份。
  • minusDays() – 返回给定时间段的副本,其中减去指定天数。
  • multipliedBy(scalar) – 返回一个新实例,该实例中的每个元素都乘以指定的标量。
Period period = Period.ofDays(5);

Period periodDaysAdded = period.plus(5);
Period periodPlus1Year = period.plusYears(1L);

在评论中向我发送有关将 Java 8 时间段用于日期差异的问题和建议。

学习愉快!

下载源码