LocalDate,LocalTime,LocalDateTime,ZonedDateTime,Date总结

LocalDate,LocalTime,LocalDateTime,ZonedDateTime,Date

最近用到了这几个类,顺便总结一下
LocalDate,LocalTime,LocalDateTime,ZonedDateTime都是Java8+中的新增的时间类API,位于java.time包下,而Date是旧有的。

LocalDate

LocalDate表示一个日期的值(年,月,日),没有时间和时区的概念,它是不可变的(immutable),是线程安全的。可以用来存储和操作日期。

LocalTime

LocalTime表示一个时间的值(时,分,秒,纳秒),没有日期和时区的概念,它是不可变的(immutable),是线程安全的。可以用来存储和操作时间。

LocalDateTime

LocalDateTime表示一个日期时间的值(年,月,日,时,分,秒,纳秒),没有时区的概念,它是不可变的(immutable),是线程安全的。可以用来存储和操作日期时间。

ZonedDateTime

ZonedDateTime用于表示带时区信息的日期时间,其中包含了日期,时间,时区,偏移量,可以精确的表示某个特定时刻的日期和时间,是不可变的,是线程安全的。

Date

Date是java.util包下的时间日期类,非线程安全,不支持国际化和时区,不推荐使用。

LocalDate,LocalTime,LocalDateTime,Date相关代码

//当前日期
LocalDate currentDate = LocalDate.now();
System.out.println("currentDate: " + currentDate);
//当前时间
LocalTime currentTime = LocalTime.now();
System.out.println("currentTime: " + currentTime);
//当前日期和时间
LocalDateTime currentDateTime = LocalDateTime.now();
System.out.println("currentDateTime: " + currentDateTime);
//Date 当前时间
Date now = new Date();
System.out.println(now);

在这里插入图片描述

LocalDate,LocalDateTime转为Date

//LocalDate转为Date
LocalDate currentDate = LocalDate.now();
Date localDateToDate = Date.from(currentDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
System.out.println("localDateToDate: " + localDateToDate);
//LocalDateTime转为Date
LocalDateTime currentDateTime = LocalDateTime.now();
Date localDateTimeToDate = Date.from(currentDateTime.atZone(ZoneId.systemDefault()).toInstant());
System.out.println("localDateTimeToDate: " + localDateTimeToDate);

在这里插入图片描述
注:LocalTime不能直接转为Date

Date转为LocalDate,LocalDateTime

//Date转为LocalDate
Date now = new Date();
LocalDate dateToLocalDate = now.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
System.out.println("dateToLocalDate: " + dateToLocalDate);
//Date转为LocalDateTime
LocalDateTime dateToLocalDateTime = LocalDateTime.ofInstant(now.toInstant(), ZoneId.systemDefault());
System.out.println("dateToLocalDateTime: " + dateToLocalDateTime);

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值