Java8 日期/時間(Date Time)使用簡介,java8date

來源:互聯網
上載者:User

Java8 日期/時間(Date Time)使用簡介,java8date

特別說明: 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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.