分享一下最近看過的文章
New Java Time (Java8 SE)
http://ingramchen.io/blog/2014/02/brand-new-java-time.html
文章擷取
----------------------------------------------------------------------------------------------------------------
java.time.* API
首先來看 java.time 提供的新 API,它引進相當多的 class。好在常用的就只有幾個:LocalDateTime、Instant、ZoneOffset、Clock。轉換的第一步驟是將過去使用
Date
物件的地方,都換成 LocalDate*
,下面是一個常見的帳戶 entity:public class Person {
String name;
LocalDate birthday;
LocalDateTime createTime;
LocalDateTime lastLoginTime;
//你幾歲
int age(LocalDate refDate) {
return Period.between(birthday, refDate).getYears();
}
//生日到了沒?
boolean isBirthday(MonthDay refDay) {
return MonthDay.from(birthday).equals(refDay);
}
//距上次登入已經過了幾天
long lastLoginDaySince(LocalDateTime refTime) {
return Duration.between(lastLoginTime, refTime).toDays();
}
}
//測試
@Test
public void variousDate() {
LocalDate birthday = LocalDate.of(1985, 3, 16);
LocalDateTime createTime = LocalDateTime.of(2014, 2, 3, 5, 0);
LocalDateTime lastLoginTime = LocalDateTime.of(2014, 2, 7, 19, 11);
Person person = new Person("Ingram",
birthday, createTime, lastLoginTime);
LocalDate today = LocalDate.of(2014, 2, 28);
assertEquals(28, person.age(today));
assertTrue(person.isBirthday(MonthDay.of(3, 16)));
LocalDateTime now = LocalDateTime.of(today, LocalTime.of(14, 51));
assertEquals(20, person.lastLoginDaySince(now));
}