2019-08-29 Java8时间操作

java.time

LocalDate 只包含日期

LocalTime 只包含时间

LocalDateTime 包含日期和时间

相互转换

  • LocalDate/LocalDateTime转Date

    Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant());
    
    Date.from(LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant());
    Date.from(LocalDate.now().atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
    
  • LocalDate/LocalDateTime转字符串

    LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    
    LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyy-MM-dd"));
    
  • Date转LocalDate和LocalDateTime

    LocalDateTime.ofInstant(new Date().toInstant());
    LocalDateTime.ofInstant(new Date().toInstant(), ZoneId.systemDefault()).toLocalDate();
    
  • 字符串转LocalDate和LocalDateTime

    LocalDateTime.parse("2019-09-01 00:01:02", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    
    LocalDate.parse("2019-09-01");
    
    

时间比较

isAfter/isBefore

时间间隔

//基于日期时间数量的间隔,比如 1天/2周/3年
Period.between(LocalDate.now(), LocalDate.now().plusDays(3)).getDays(); 

//基于精确时间的间隔,比如1秒/1000纳秒
Duration.between(LocalDateTime.now(),LocalDateTime.now().plusMinutes(2)).getSeconds(); // 120
Duration.between(LocalDateTime.now(),LocalDateTime.now(ZoneId.of("Europe/London"))).getSeconds()); //-25200
Duration.between(LocalDateTime.now(),LocalDateTime.now(ZoneId.of("Europe/London"))).toHours()); //01
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容