Java Reference
In-Depth Information
Finally, Listing 12-14 contains an example of combining two partials to get another partial. It's the complete
program to compute Christmas days for the next five years.
Listing 12-14. Combining a Year and MonthDay to get a LocalDate
// ChristmasDay.java
package com.jdojo.datetime;
import java.time.LocalDate;
import java.time.Month;
import java.time.MonthDay;
import java.time.Year;
import java.time.format.TextStyle;
import java.util.Locale;
public class ChristmasDay {
public static void main(String[] args) {
MonthDay dec25 = MonthDay.of(Month.DECEMBER, 25);
Year year = Year.now();
// Construct and print Christmas days in next five years
for (int i = 1; i <= 5; i++) {
LocalDate ld = year.plusYears(i).atMonthDay(dec25);
int yr = ld.getYear();
String weekDay = ld.getDayOfWeek()
.getDisplayName(TextStyle.FULL, Locale.getDefault());
System.out.format("Christmas in %d is on %s.%n", yr, weekDay);
}
}
}
Christmas in 2015 is on Friday.
Christmas in 2016 is on Sunday.
Christmas in 2017 is on Monday.
Christmas in 2018 is on Tuesday.
Christmas in 2019 is on Wednesday.
The program creates a MonthDay partial for December 25 and keeps combining a year to it to get a LocalDate .
You can rewrite the program in Listing 12-14 using the LocalDate class as shown below. It shows the versatility of the
Date-Time API, which allows you do achieve the same result in different ways.
LocalDate ld = LocalDate.of(Year.now().getValue(), Month.DECEMBER, 25);
for (int i = 1; i <= 5; i++) {
ld = ld.withYear(ld.getYear() + 1);
// format and print ld here
}
Search WWH ::




Custom Search