zoukankan      html  css  js  c++  java
  • Convert Date between LocalDateTime

    http://blog.progs.be/542/date-to-java-time

    Java8 has new date and time classes to “replace” the old not-so-beloved java.util.Date class.

    Unfortunately though, converting between the two is somewhat less obvious than you might expect.

    Convert java.util.Date to java.time.LocalDateTime

    Date ts = ...;
    Instant instant = Instant.ofEpochMilli(ts.getTime());
    LocalDateTime res = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());

    The big trick (for all these conversions) is to convert to Instant. This can be converted to LocalDateTime by telling the system which timezone to use. This needs to be the system default locale, otherwise the time will change.

    Convert java.util.Date to java.time.LocalDate

    Date date = ...;
    Instant instant = Instant.ofEpochMilli(date.getTime());
    LocalDate res = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()).toLocalDate();

    Convert java.util.Date to java.time.LocalTime

    Date time = ...;
    Instant instant = Instant.ofEpochMilli(time.getTime());
    LocalTime res = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()).toLocalTime();

    Convert java.time.LocalDateTime to java.util.Date

    LocalDateTime ldt = ...;
    Instant instant = ldt.atZone(ZoneId.systemDefault()).toInstant();
    Date res = Date.from(instant);

    Convert java.time.LocalDate to java.util.Date

    LocalDate ld = ...;Instant instant = ld.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();
    Date res = Date.from(instant);

    Convert java.time.LocalTime to java.util.Date

    LocalTime lt = ...;
    Instant instant = lt.atDate(LocalDate.of(A_YEAR, A_MONTH, A_DAY)).
            atZone(ZoneId.systemDefault()).toInstant();
    Date time = Date.from(instant);

    This one is a little, funny, you need to inject a date to convert the time… Gives you the option of start of epoch or something else.

  • 相关阅读:
    Windows7在自由的虚拟机(微软官方虚拟机)
    POJ1135_Domino Effect(最短)
    项目优化经验分享(七)敏捷开发
    POJ 3299 Humidex(简单的问题)
    NEFUOJ 500 二分法+最大流量
    json 解析解乱码
    【设计模式】Abstract Factory模式
    汇编语言的应用
    Duanxx的STM32学习:NVIC操作
    PHP移动互联网的发展票据(6)——MySQL召回数据库基础架构[1]
  • 原文地址:https://www.cnblogs.com/feika/p/4448573.html
Copyright © 2011-2022 走看看