Given the code fragment:
LocalDate date1 = LocalDate.now();
LocalDate date2 = LocalDate.of(2014, 6, 20);
LocalDate date3 = LocalDate.parse("2014-06-20", DateTimeFormatter.ISO_DATE);
System.out.println("date1 = " + date1);
System.out.println("date2 = " + date2);
System.out.println("date3 = " + date3);
Assume that the system date is June 20, 2014. What is the result?
A.
date1 = 2014-06-20
date2 = 2014-06-20
date3 = 2014-06-20
date2 = 2014-06-20
date3 = 2014-06-20
B.
date1 = 06/20/2014
date2 = 2014-06-20
date3 = Jun 20, 2014
date2 = 2014-06-20
date3 = Jun 20, 2014
C. Compilation fails.
D. A DateParseException is thrown at runtime.
題解
這題是在考Java 8加入的日期與時間(Date-Time)API,可以參考以下文章:
now、of、parse都是建立LocalDate物件的方式。parse可以將字串使用指定的DateTimeFormatter格式化成日期與時間的物件,在這題程式中要格式化的字串是「2014-06-20」,符合ISO_DATE這個DateTimeFormatter的格式。
LocalDate預設的toString方法會將日期以ISO-8601標準格式轉成字串。