This method
adds this period to the specified temporal object. The returned temporal object is of the same type as of the input
type.
package com.logicbig.example.period;
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.Temporal;
public class AddToExample {
public static void main(String... args) {
Period p = Period.of(2, 5, 10);
System.out.println(p);
LocalDate d = LocalDate.now();
System.out.println(d);
Temporal t = p.addTo(d);
System.out.printf("temporal Class: %s%n", t.getClass());
System.out.printf("temporal value: %s%n", t);
}
}
Output
P2Y5M10D
2017-05-01
temporal Class: class java.time.LocalDate
temporal value: 2019-10-11
package com.logicbig.example.period;
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.Temporal;
public class AddToExample2 {
public static void main(String... args) {
Period p = Period.of(-2, -5, -10);
System.out.println(p);
LocalDate d = LocalDate.now();
System.out.println(d);
Temporal t = p.addTo(d);
System.out.println(t);
}
}
Output
P-2Y-5M-10D
2017-05-01
2014-11-21
package com.logicbig.example.period;
import java.time.*;
import java.time.temporal.Temporal;
public class AddToExample3 {
public static void main(String... args) {
Period p = Period.of(10, 2, 13);
System.out.println(p);
add(LocalDate.now(), p);
add(LocalDateTime.now(), p);
add(OffsetDateTime.now(), p);
add(ZonedDateTime.now(), p);
}
private static void add(Temporal t, Period p) {
Temporal t2 = p.addTo(t);
String s = t2.getClass().getSimpleName();
System.out.printf("%15s > %s > %s%n", s, t, t2);
}
}
Output
P10Y2M13D
LocalDate > 2017-05-01 > 2027-07-14
LocalDateTime > 2017-05-01T15:54:58.816 > 2027-07-14T15:54:58.816
OffsetDateTime > 2017-05-01T15:54:58.816-05:00 > 2027-07-14T15:54:58.816-05:00
ZonedDateTime > 2017-05-01T15:54:58.817-05:00[America/Chicago] > 2027-07-14T15:54:58.817-05:00[America/Chicago]