Java 8 中引入的java.time套件包含數個處理日期與時間的類別。
LocalDatejava.time.LocalDate類別代表 ISO-8601 曆法系統 中不帶時區的日期,例如2007-12-03:
LocalDate date = LocalDate.of(2007, 12, 3);
日期可以和其他日期互相比較:
LocalDate date1 = LocalDate.of(2007, 12, 3);
LocalDate date2 = LocalDate.of(2007, 12, 4);
date1.isBefore(date2);
// => true
date1.isAfter(date2);
// => false
LocalDate實例提供了一些 getter,可以從中取得日期時間的各個部分:
LocalDate date = LocalDate.of(2007, 12, 3);
date.getDayOfMonth();
// => 3
LocalDate實例有方法可以為它加上時間單位:
這些方法會回傳一個_新_的LocalDate實例,不會更新現有的實例,因為LocalDate類別是不可變的。
LocalDate date = LocalDate.of(2007, 12, 3);
date.plusDays(3);
// => 2007-12-06
LocalDateTimejava.time.LocalDateTime類別代表 ISO-8601 曆法系統 中不帶時區的日期時間,例如2007-12-03T10:15:30:
LocalDateTime datetime = LocalDateTime.of(2007, 12, 3, 10, 15, 30);
你可以把LocalDate實例轉換成LocalDateTime:
LocalDate date = LocalDate.of(2007, 12, 3);
LocalDateTime datetime = date.atTime(10, 15, 30);
datetime.toString();
// => "2007-12-03T10:15:30"
LocalDate和LocalDateTime在與String互相轉換時,都使用 ISO-8601 標準表示法。
LocalDateTime datetime = LocalDateTime.of(2007, 12, 3, 10, 15, 30);
LocalDateTime parsed = LocalDateTime.parse("2007-12-03T10:15:30");
datetime.isEqual(parsed);
// => true
如果想用不同的格式,像這樣從String解析出LocalDate或LocalDateTime,是沒辦法做到的。
因此,如果想用自訂格式來格式化日期,就應該使用java.time.format.DateTimeFormatter:
DateTimeFormatter parser = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate date = LocalDate.parse("03/12/2007", parser);
DateTimeFormatter printer = DateTimeFormatter.ofPattern("MMMM d, yyyy");
printer.format(date);
// => "December 3, 2007"
建立自訂格式時,也可以指定地區設定,以便針對不同區域格式化與解析日期:
DateTimeFormatter.ofPattern("MMMM d, yyyy", Locale.FRENCH).format(date);
// => décembre 3, 2007
DateTimeFormatter.ofPattern("MMMM d, yyyy", Locale.of("pt")).format(date);
// => dezembro 3, 2007
在這道練習中,你將為一間位於紐約、於 2012 年 9 月 15 日開幕的美容沙龍開發預約排程系統。
實作AppointmentScheduler.schedule()方法,將預約日期的文字表示法解析成對應的LocalDateTime:
AppointmentScheduler scheduler = new AppointmentScheduler();
scheduler.schedule("7/25/2019 13:45:00");
// => LocalDateTime.of(2019, 7, 25, 13, 45, 0)
實作AppointmentScheduler.hasPassed()方法,它會接收一個預約日期,並檢查該預約是否發生在過去的某個時間點:
AppointmentScheduler scheduler = new AppointmentScheduler();
scheduler.hasPassed(LocalDateTime.of(1999, 12, 31, 9, 0, 0));
// => true
實作AppointmentScheduler.isAfternoonAppointment()方法,它會接收一個預約日期,並檢查該預約是否在下午(>= 12:00 且 < 18:00):
AppointmentScheduler scheduler = new AppointmentScheduler();
scheduler.isAfternoonAppointment(LocalDateTime.of(2019, 03, 29, 15, 0, 0))
// => true
實作AppointmentScheduler.getDescription()方法,它會接收一個預約日期,並回傳該日期與時間的描述:
AppointmentScheduler scheduler = new AppointmentScheduler();
scheduler.getDescription(LocalDateTime.of(2019, 03, 29, 15, 0, 0))
// => "You have an appointment on Friday, March 29, 2019, at 3:00 PM."
實作AppointmentScheduler.getAnniversaryDate()方法,回傳今年的週年紀念日,也就是 9 月 15 日:
AppointmentScheduler scheduler = new AppointmentScheduler();
scheduler.getAnniversaryDate()
// => LocalDate.of(<current year>, 9, 15)