小窝

Java8中LocalTime,LocalDate,Date,Calendar之间的转换

发布时间:6年前作者:shine热度: 4804 ℃评论数:

Java8 时间类型之间的转换,代码如下

public static void main(String[] args) {
    LocalDateTime localDateTime = LocalDateTime.now();
    LocalDate localDate = LocalDate.now();
    Date date = new Date();
    Calendar calendar = Calendar.getInstance();

    System.out.println("Date 转 LocalDateTime:" + LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()));

    System.out.println("Calendar 转 LocalDateTime:" + LocalDateTime.ofInstant(calendar.toInstant(), ZoneId.systemDefault()));

    System.out.println("Calendar 转 Date:" + calendar.getTime());

    System.out.println("LocalDateTime 转 LocalDate:" + localDateTime.toLocalDate());

    System.out.println("LocalDate 转 LocalDateTime:" + localDate.atStartOfDay());

    //通过此种转化可能会存在时区上的差异
    System.out.println("LocalDateTime 转 Date:" + Date.from(localDateTime.toInstant(ZoneOffset.UTC)));

    System.out.println("LocalDateTime 转 Date:" + Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()));

    //通过 Calendar 的 set 方法可以将 LocalDateTime 转为 Calendar
    calendar.set(localDateTime.getYear(), (localDateTime.getMonthValue() - 1), localDateTime.getDayOfMonth(), localDateTime.getMinute(), localDateTime.getSecond());
    System.out.println("LocalDateTime 转 Calendar:" + calendar.getTime());

}

热门评论

手机扫码访问