Date与LocalDateTime的相互转换

本文详细介绍了如何在Java中将Date对象转换为LocalDateTime对象,以及如何反过来将LocalDateTime转换为Date对象,涉及toInstant(),atZone(),和Date.from()等关键方法的使用。
摘要由CSDN通过智能技术生成

Date对象转换为LocalDateTime

步骤:
    1.拿到要转换的Date对象
    2.将Date对象转换成为Instant对象
        方法:
            Date对象.toInstant()
    3.将瞬时对象转换成为LocalDateTime对象
		方法:
			LocalDateTime.ofInstant(瞬时对象,时区);
/**
*相关代码
*/
//将Date对象转换为LocalDateTime
Date date = new Date();
Instant instant = date.toInstant();
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
		

LocalDateTime对象转换为Date对象

步骤:
1,拿到要转换的LocalDateTime对象
2,将LocalDateTime对象转换成为时区对象
	方法:
		LocalDateTime对象.atZone(时区);//得到时区对象
3.将2中得到的时区对象转换成为瞬时对象
	方法;
		时区对象.toInstant()//得到瞬时对象
4.通过Date提供的静态方法将3中得到的瞬时对象转换为我们需要的Date对象
	方法:
		Date date = Date.from(瞬时对象);
/**
*相关代码
*/
//将LocalDateTime对象转换为Date对象
LocalDateTime dateTime = LocalDateTime.now();
ZonedDateTime zonedDateTime = dateTime.atZone(ZoneId.systemDefault());
Instant instant2 = zonedDateTime.toInstant();
Date date2 = Date.from(instant2);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值