Skip to content

Commit a7fbe14

Browse files
committed
Add example for java.time.Period
1 parent b8e2a1f commit a7fbe14

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package io.javaalmanac.snippets.time;
2+
3+
import java.time.LocalDate;
4+
import java.time.Period;
5+
import java.time.ZoneId;
6+
7+
/**
8+
* A date-based amount of time can be represented with the
9+
* {@link java.time.Period} type. With this data type a time span is expressed
10+
* as a number of years, months and days.
11+
*
12+
* @title Time Period
13+
* @category api.time
14+
* @since 8
15+
*/
16+
public class HowOldIsJava {
17+
18+
static final LocalDate BIRTHDAY_OF_JAVA = LocalDate.of(1995, 5, 23);
19+
20+
static final ZoneId TIMEZONE_OF_BIRTH = ZoneId.of("America/Los_Angeles");
21+
22+
public static void main(String[] args) {
23+
24+
var today = LocalDate.now(TIMEZONE_OF_BIRTH);
25+
var age = Period.between(BIRTHDAY_OF_JAVA, today);
26+
System.out.println("As of today Java is %s old".formatted(fmt(age)));
27+
28+
var nextAnivesary = BIRTHDAY_OF_JAVA.plus(Period.ofYears(age.getYears() + 1));
29+
var tillAnivesary = Period.between(today, nextAnivesary);
30+
System.out.println("Java's next birthday is in %s".formatted(fmt(tillAnivesary)));
31+
32+
}
33+
34+
static String fmt(Period p) {
35+
// Unfortunately there is no built-in formatter for Period objects
36+
return "%d years, %d months and %d days".formatted(p.getYears(), p.getMonths(), p.getDays());
37+
}
38+
39+
}

0 commit comments

Comments
 (0)