LocalDateTime ZonedDateTime Instant 的相互转换

LocalDateTime ZonedDateTime Instant 的相互转换

1. 概念

类名描述示例
LocalDateTime本地日期时间2022-06-15T22:06:29.483
ZonedDateTime带时区的日期时间2022-06-15T22:06:29.483+08:00[Asia/Shanghai]
Instant时间戳1655301989483

2. 常用java代码

package com.ysx.utils.datetime;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;

/**
 * @author youngbear
 * @email youngbear@aliyun.com
 * @date 2022/6/26 22:22
 * @blog https://blog.csdn.net/next_second
 * @github https://github.com/YoungBear
 * @description LocalDateTime ZonedDateTime Instant 的相互转换
 */
public class ConvertUtils {

    /**
     * 将 ZonedDateTime 转换为 LocalDateTime
     *
     * @param zonedDateTime 带时区的日期时间
     * @return 本地日期时间
     */
    public static LocalDateTime zoned2Local(ZonedDateTime zonedDateTime) {
        return zonedDateTime.toLocalDateTime();
    }

    /**
     * 将 LocalDateTime 转换为 ZonedDateTime
     *
     * @param localDateTime 本地日期时间
     * @param zoneId        时区
     * @return 带时区的日期时间
     */
    public static ZonedDateTime local2Zoned(LocalDateTime localDateTime, ZoneId zoneId) {
        return ZonedDateTime.of(localDateTime, zoneId);
    }

    /**
     * 将 Instant 转换为 LocalDateTime
     *
     * @param instant 时间戳
     * @param zoneId  时区
     * @return 本地日期时间
     */
    public static LocalDateTime instant2local(Instant instant, ZoneId zoneId) {
        return instant.atZone(zoneId).toLocalDateTime();
    }

    /**
     * 将 LocalDateTime 转换为 Instant
     *
     * @param localDateTime 本地日期时间
     * @param zoneId        时区
     * @return 时间戳
     */
    public static Instant local2Instant(LocalDateTime localDateTime, ZoneId zoneId) {
        return localDateTime.atZone(zoneId).toInstant();
    }


    /**
     * 将 Instant 转换为 ZonedDateTime
     *
     * @param instant 时间戳
     * @param zoneId  时区
     * @return 带时区的日期时间
     */
    public static ZonedDateTime instant2Zoned(Instant instant, ZoneId zoneId) {
        return instant.atZone(zoneId);
    }

    /**
     * 将 ZonedDateTime 转换为 Instant
     *
     * @param zonedDateTime 带时区的日期时间
     * @return 时间戳
     */
    public static Instant zoned2Instant(ZonedDateTime zonedDateTime) {
        return zonedDateTime.toInstant();
    }
}

单元测试:

package com.ysx.utils.datetime;

import org.junit.Assert;
import org.junit.Test;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author youngbear
 * @email youngbear@aliyun.com
 * @date 2022/6/26 22:40
 * @blog https://blog.csdn.net/next_second
 * @github https://github.com/YoungBear
 * @description
 */
public class ConvertUtilsTest {

    @Test
    public void testZonedDateTime() {
        String zonedDateTimeString = "2022-06-15T22:06:29.483+08:00[Asia/Shanghai]";
        DateTimeFormatter formatter = DateTimeFormatter.ISO_ZONED_DATE_TIME;
        ZonedDateTime zonedDateTime = ZonedDateTime.parse(zonedDateTimeString, formatter);

        // zoned2Local
        LocalDateTime localDateTime = ConvertUtils.zoned2Local(zonedDateTime);
        String localDateTimeString = "2022-06-15T22:06:29.483";
        Assert.assertEquals(localDateTimeString, localDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
        // zoned2Instant
        Instant instant = ConvertUtils.zoned2Instant(zonedDateTime);
        long timestamp = 1655301989483L;
        Assert.assertEquals(timestamp, instant.toEpochMilli());
    }

    @Test
    public void testLocalDateTime() {
        String localDateTimeString = "2022-06-15T22:06:29.483";
        LocalDateTime localDateTime = LocalDateTime.parse(localDateTimeString, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
        ZoneId zoneId = ZoneId.of("Asia/Shanghai");

        // local2Zoned
        ZonedDateTime zonedDateTime = ConvertUtils.local2Zoned(localDateTime, zoneId);
        String zonedDateTimeString = "2022-06-15T22:06:29.483+08:00[Asia/Shanghai]";
        Assert.assertEquals(zonedDateTimeString, zonedDateTime.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
        // local2Instant
        Instant instant = ConvertUtils.local2Instant(localDateTime, zoneId);
        long timestamp = 1655301989483L;
        Assert.assertEquals(timestamp, instant.toEpochMilli());
    }

    @Test
    public void testInstant() {
        long timestamp = 1655301989483L;
        Instant instant = Instant.ofEpochMilli(timestamp);
        ZoneId zoneId = ZoneId.of("Asia/Shanghai");

        // instant2local
        LocalDateTime localDateTime = ConvertUtils.instant2local(instant, zoneId);
        String localDateTimeString = "2022-06-15T22:06:29.483";
        Assert.assertEquals(localDateTimeString, localDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));

        // instant2Zoned
        ZonedDateTime zonedDateTime = ConvertUtils.instant2Zoned(instant, zoneId);
        String zonedDateTimeString = "2022-06-15T22:06:29.483+08:00[Asia/Shanghai]";
        Assert.assertEquals(zonedDateTimeString, zonedDateTime.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
    }

}

相关文章

1. LocalDateTime ZonedDateTime Instant 的相互转换

2. 日期时间格式化与解析

3. 带时区时间日期 ZonedDateTime

4. 夏令时

源代码地址

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
廖雪峰 Java 教程 Java教程 Java快速入门 Java简介 安装JDK 第一个Java程序 Java代码助手 使用IDE 使用IDE练习插件 Java程序基础 Java程序基本结构 变量和数据类型 整数运算 浮点数运算 布尔运算 字符和字符串 数组类型 流程控制 输入和输出 if判断 switch多重选择 while循环 do while循环 for循环 break和continue 数组操作 遍历数组 数组排序 多维数组 命令行参数 面向对象编程 面向对象基础 方法 构造方法 方法重载 继承 多态 抽象类 接口 静态字段和静态方法 包 作用域 classpath和jar 模块 Java核心类 字符串和编码 StringBuilder StringJoiner 包装类型 JavaBean 枚举类 BigInteger BigDecimal 常用工具类 异常处理 Java的异常 捕获异常 抛出异常 自定义异常 使用断言 使用JDK Logging 使用Commons Logging 使用Log4j 使用SLF4J和Logback 反射 Class类 访问字段 调用方法 调用构造方法 获取继承关系 动态代理 注解 使用注解 定义注解 处理注解 泛型 什么是泛型 使用泛型 编写泛型 擦拭法 extends通配符 super通配符 泛型和反射 集合 Java集合简介 使用List 编写equals方法 使用Map 编写equals和hashCode 使用EnumMap 使用TreeMap 使用Properties 使用Set 使用Queue 使用PriorityQueue 使用Deque 使用Stack 使用Iterator 使用Collections IO File对象 InputStream OutputStream Filter模式 操作Zip 读取classpath资源 序列化 Reader Writer PrintStream和PrintWriter 日期与时间 基本概念 Date和Calendar LocalDateTime ZonedDateTime DateTimeFormatter Instant 最佳实践 单元测试 编写JUnit测试 使用Fixture 异常测试 条件测试 参数化测试
### 回答1: LocalDateTime和Date之间的转换可以通过以下方式实现: 1. LocalDateTime转Date: ``` LocalDateTime localDateTime = LocalDateTime.now(); Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()); ``` 2. Date转LocalDateTime: ``` Date date = new Date(); LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()); ``` ### 回答2: LocalDateTime和Date的转化可以通过以下方法进行: 1. LocalDateTime转Date:可以使用java.util.Date类中的from()方法,将LocalDateTime对象转化为Date对象。具体步骤如下: ```java LocalDateTime localDateTime = LocalDateTime.now(); Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()); ``` 2. Date转LocalDateTime:可以使用java.util.Date类中的toInstant()方法,将Date对象转化为Instant对象,然后再通过Instant对象的atZone()方法指定时区,得到对应的ZonedDateTime对象,最后使用ZonedDateTime对象的toLocalDateTime()方法得到LocalDateTime对象。具体步骤如下: ```java Date date = new Date(); LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()); ``` 需要注意的是,LocalDateTime是Java 8引入的新的日期时间类,精确到纳秒级别,而Date是Java早期版本提供的日期时间类,精确到毫秒级别。转化过程中,可能会有精度的损失。同时,LocalDateTime类与时区无关,而Date默认使用系统默认时区。 另外,推荐在使用时尽可能使用新的Java 8日期时间类(LocalDateTime、LocalDate、LocalTime等),因为它们更加灵活,提供了更多的方法和功能,并且在并发环境下也更加安全。如果必须要使用旧的Date类,可以在需要时进行转化。 ### 回答3: LocalDateTime 是 Java 8 中的一个日期时间类,用于表示不带时区信息的日期时间。而 Date 是 Java 中的旧日期时间类,用于表示有时区信息的日期时间。本文将介绍 LocalDateTime 和 Date 之间的转化。 要将 LocalDateTime 转换为 Date,可以使用以下代码: ``` LocalDateTime localDateTime = LocalDateTime.now(); ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.systemDefault()); Date date = Date.from(zonedDateTime.toInstant()); ``` 首先,通过 LocalDateTime 的 now() 方法获取当前的本地日期时间。然后,使用 atZone() 方法将 LocalDateTime 对象与系统默认时区关联起来,构建一个 ZonedDateTime 对象。最后,通过 toInstant() 方法将 ZonedDateTime 转换Instant 对象,并使用 Date 的 from() 方法将 Instant 转换为 Date 对象。 要将 Date 转换LocalDateTime,可以使用以下代码: ``` Date date = new Date(); Instant instant = date.toInstant(); LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()); ``` 首先,创建一个 Date 对象。然后,使用 toInstant() 方法将 Date 转换Instant 对象。最后,使用 LocalDateTime 的 ofInstant() 方法将 Instant 转换LocalDateTime 对象,需要传入 Instant 对象和系统默认时区。 通过这些转化方式,我们可以在 LocalDateTime 和 Date 之间进行转化,以便在不同的日期时间处理场景中使用。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值