Java Reference
In-Depth Information
An instance of the Period class represents a period. Use one of the following static factory methods to
create a Period :
static Period of(int years, int months, int days)
static Period ofDays(int days)
static Period ofMonths(int months)
static Period ofWeeks(int weeks)
static Period ofYears(int years)
The following snippet of code creates some instances of the Period class:
Period p1 = Period.of(2, 3, 5); // 2 years, 3 months, and 5 days
Period p2 = Period.ofDays(25); // 25 days
Period p3 = Period.ofMonths(-3); // -3 months
Period p4 = Period.ofWeeks(3); // 3 weeks (21 days)
System.out.println(p1);
System.out.println(p2);
System.out.println(p3);
System.out.println(p4);
P2Y3M5D
P25D
P-3M
P21D
You can perform additions, subtractions, multiplications, and negation on a period. The division operation
performs an integer division, for example, 7 divided by 3 is 2. The following snippet of code shows some of the
operations and their results on periods:
Period p1 = Period.ofDays(15); // P15D
Period p2 = p1.plusDays(12); // P27D
Period p3 = p1.minusDays(12); // P3D
Period p4 = p1.negated(); // P-15D
Period p5 = p1.multipliedBy(3); // P45D
Use the plus() and minus() methods of the Period class to add one period to another and to subtract one period
from another. Use the normalized() method of the Period class to normalize the years and months. The method
ensures that the month value stays within 0 to 11. For example, a period of “2 years and 15 months” will be normalized
to “3 years and 3 months.”
Period p1 = Period.of(2, 3, 5);
Period p2 = Period.of(1, 15, 28);
System.out.println("p1: " + p1);
System.out.println("p2: " + p2);
System.out.println("p1.plus(p2): " + p1.plus(p2));
System.out.println("p1.plus(p2).normalized(): " + p1.plus(p2).normalized());
System.out.println("p1.minus(p2): " + p1.minus(p2));
Search WWH ::




Custom Search