特别說明: LocalDateTime 為日期時間的計算提供了很大的友善, 在構造對象/運算/toString等友善都非常便利。
3個常用的類:
java.time.LocalDateTime;
java.time.LocalDate;
java.time.LocalTime;
推薦多使用 LocalDateTime
常用表達式:
現在: LocalDateTime now = LocalDateTime.now();
今天: LocalDate today = LocalDate.now();
從屬性建立對象:
LocalDateTime.of(int year, Month month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond)
互相轉換:
LocalDate date = localDateTime.toLocalDate();
LocalDateTime dateTime = localDate.atStartOfDay();
LocalTime time = localDateTime.toLocalTime();
LocalDateTime dateTime = localTime.atDate(localDate);
LocalDateTime dateTime = LocalDateTime.of(date.getYear() + 1900, date.getMonth() + 1, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
Date date = new Date(localDateTime.getYear() - 1900, localDateTime.getMonthValue() - 1, localDateTime.getDayOfMonth(), localDateTime.getHour(), localDateTime.getMinute(), localDateTime.getSecond()); //會丢失 nanoOfSecond
元件相容性:
- myBatis (mybatis-spring v1.3.0) 暫不支援 localDateTime
- Json (com.fasterxml.jackson.core v2.5.4) 貌似也沒特别的支援, 序列化的結果如下:
{
"month": "DECEMBER",
"year": 2017,
"dayOfMonth": 7,
"dayOfWeek": "THURSDAY",
"dayOfYear": 341,
"monthValue": 12,
"hour": 10,
"minute": 4,
"nano": 228000000,
"second": 58,
"chronology": {
"id": "ISO",
"calendarType": "iso8601"
}
}
是以, 在與 資料庫 互動, 與 Json 互動時還是建議使用 java.util.Date
總結:
目前情況下, 業務計算建議使用 LocalDateTime, 業務計算以外建議轉化為 Date
By the way:
LocalDateTime 為日期時間的計算提供了很大的友善, 還有諸多其它優點。詳細内容 Java8 日期/時間(Date Time)API指南](http://www.importnew.com/14140.html
部落客簡介:佘煥敏(shé),洋名 Billy Sir。
關注程式設計基礎技術,并緻力于研究軟體的自動化生成。
對程式設計規範化、面向對象的極緻使用也有着濃厚的興趣。
同時非常希望能夠寫程式到65歲。
隻有工匠精神,才能把常人覺得單調乏味的代碼,當作作品雕刻成藝術品。