zoukankan      html  css  js  c++  java
  • Java8 日期/时间(Date Time)使用简介

    特别说明: 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

  • 相关阅读:
    团队项目-需求分析报告
    团队项目-选题报告
    第一次结对编程作业
    第一次编程作业
    第一次作业
    第10组 Beta冲刺(2/4)
    第10组 Beta冲刺(1/4)
    第10组 Alpha冲刺(4/4)
    第10组 团队Git现场编程实战
    第二次结对编程作业
  • 原文地址:https://www.cnblogs.com/BillySir/p/7998400.html
Copyright © 2011-2022 走看看