Java8学习笔记:LocalDateTime、Instant 和 OffsetDateTime 相互转换

本文主要是介绍Java8学习笔记:LocalDateTime、Instant 和 OffsetDateTime 相互转换,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

环境

Java 1.8+
IDEA:2019.2.4

前言

最近在写接口 由遇到了LocalDate或者LocalDateTimeOffsetDatetime的问题;
遇到这个时,总是有点懵;今天花时间总结下

Java8中时间api

推荐使用的是:

LocalDate
LocalTime
Insant
Duration
Period

OffsetDatetime 转 字符串

String DATE_TIME_SECOND_STRING = "yyyy-MM-dd HH:mm:ss";
OffsetDateTime offsetDateTime = 2019-10-10T00:00+08:00
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(DATE_TIME_SECOND_STRING);
String result = dateTimeFormatter.format(offsetDateTime);

offsetDateTime 在程序中的值,如下图:
在这里插入图片描述

字符串 转 OffsetDatetime

String DATE_TIME_SECOND_STRING = "yyyy-MM-dd HH:mm:ss";
String value = "2019-10-10 00:00:00";
// 方法一
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(DATE_TIME_SECOND_STRING);
LocalDateTime parse1 = LocalDateTime.parse(value, dateTimeFormatter);
// 结果
OffsetDateTime offsetDateTime = ZonedDateTime.of(parse1, ZoneId.systemDefault()).toOffsetDateTime();
// 方法二
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(DATE_TIME_SECOND_STRING)
.withZone(ZoneId.systemDefault());
// 结果
OffsetDateTime offsetDateTime = ZonedDateTime.parse(value, dateTimeFormatter).toOffsetDateTime();

只有年份 yyyy-MM-dd的情况

String value = "2019-10-10";
// 解析的pattern也要做出相应调整
String DATE_SECOND_STRING = "yyyy-MM-dd";
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(DATE_TIME_SECOND_STRING);
// 这个地方特别注意,使用LocalDateTime会报错的
LocalDate parse = LocalDate.parse(value, dateTimeFormatter);
OffsetDateTime offsetDateTime = 
ZonedDateTime.of(LocalDateTime.of(parse, LocalTime.MIN), ZoneId.systemDefault()).toOffsetDateTime();

LocalDatetime 转 OffsetDatetime

假设我们有:

LocalDateTime localDateTime = LocalDateTime.now();

按照OffsetDateTime提供的方法:

OffsetDateTime of(LocalDateTime dateTime, ZoneOffset offset)

即我们还需要一个ZoneOffset

ZoneOffset表示的是格林威治/UTC的时区偏移量,例如+02:00

所以我们可以这么用:

OffsetDateTime.of(localDateTime, ZoneOffset.of("+8")))
//  或者
OffsetDateTime.of(localDateTime, ZoneOffset.ofHours(8))

LocalDate 转 OffsetDatetime

由上面可知,我们知道LocalDatetimeOffsetDatetime的方法

那么我们可以先将LocalDate转成LocalDatetime;

LocalDate parse = LocalDate.parse(value, dateTimeFormatter);
// 先将LocalDate转为LocalDateTime
LocalDateTime localDateTime = LocalDateTime.of(parse, LocalTime.MIN);
OffsetDateTime offsetDateTime = 
ZonedDateTime.of(localDateTime, ZoneId.systemDefault()).toOffsetDateTime();

LocalDateTime 转 Instant

根据LocalDateTime自带的方法:

localDateTime.toInstant(ZoneOffset.of(+8));
// 或者
localDateTime.toInstant(ZoneOffset.ofHours(8));

但如果使用如下方式:

Instant.ofEpochSecond(localDateTime.toEpochSecond(ZoneOffset.of("+8")));

上面这句的结果:年月日是对滴,时间的话就是伦敦时间了。

因为toEpochSecond只控制到了秒,而不是毫秒;

Instant 转 OffsetDateTime

由于Instant类中没有提供,所以就去OffsetDateTime里面找:

OffsetDateTime.ofInstant(instant, ZoneId.systemDefault())

出于这样的思路,我们LocalDateTimeOffsetDatetime,就多了一条路,

我们先LocalDateTimeInstant,然后再InstantLocalDateTime,当然这有点多此一举。

LocalDateTime、Instant 转 毫秒

看了LocalDateTime后才知道,其只提供了转的方法,并没有提供转毫秒的方法。

转秒的:

localDateTime.toEpochSecond(ZoneOffset.of("+8"))

如何转毫秒呢?

得借用Instant类中的toEpochMilli方法:

localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli()

这样就得到了毫秒;

关系图

这幅图来自于Java8实战这本书籍

在这里插入图片描述

从上面的图中我们可以看出,LocalDateTime,并不能表示我们人类世界中完整的时间,而ZonedDateTime可以。

而且上面的转换中我们可以知道,LocalDateTimeInstant或者OffsetDatetime都是需要加上偏移时区的(ZoneOffset)。

所以可以得出 OffsetDatetimeInstant也是可以表示人类世界中完整的时间的,和ZoneDateTime是等效的。

那么区别呢?

OffsetDatetime、Instant和 ZoneDateTime区别

先看下网上的答案:

OffsetDateTime, ZonedDateTime and Instant all store an instant on the time-line to nanosecond precision. Instant is the simplest, simply representing the instant. OffsetDateTime adds to the instant the offset from UTC/Greenwich, which allows the local date-time to be obtained. ZonedDateTime adds full time-zone rules.

OffsetDateTime ,ZonedDateTime 和 Instant 都会在时间线上存储一个纳秒级精度。 Instant 是最简单的,只需代表instant。 OffsetDateTime 添加到UTC / Greenwich的偏移瞬间,这允许获得本地日期时间。 ZonedDateTime 添加完整的时区规则。

Thus the difference between OffsetDateTime and ZonedDateTime is that the latter includes the rules that cover daylight saving time adjustments.

因此 OffsetDateTime 和之间的区别ZonedDateTime 是后者包括涵盖夏令时调整的规则。


个人以为:

首先Instant是给机器看的类,所以我觉得,他肯定能表示世界完整时间。
重点就是OffsetDatetimeZoneDateTime
就我上面的例子而言,我觉得没什么区别。
但根据老外的言论,那就是是否包含夏令营规则的区别

最后顺便记录一个老外的提问:

OffsetDateTime should be used when writing date to database, but I don’t get why.

当将日期写入数据库时,为什么要使用OffsetDatetime

答复:

One reason is that dates with local time offsets always represent the same instants in time, and therefore have a stable ordering. By contrast, the meaning of dates with full timezone information is unstable in the face of adjustments to the rules for the respective timezones. (And these do happen…)


Dates whose meaning / ordering is unstable are problematic if (for example) you create a database index on a field the date.

一个原因是具有局部时间偏移的日期总是代表相同的时刻,因此具有稳定的排序。 相比之下,面对对各个时区的规则进行调整,具有全时区信息的日期的含义是不稳定的。 (这些确实发生了…)

如果(例如)在日期的字段上创建数据库索引,则其含义/排序不稳定的日期会出现问题。

设置23:59:59 和 00:00:00

// 设置 23:59:59
OffsetDateTime  endDateTime = endDateTime.with(LocalTime.MAX);
// 设置 00:00:00
OffsetDateTime  endDateTime = endDateTime.with(LocalTime.MIN);

参考地址:

https://stackoverflow.com/questions/30234594/whats-the-difference-between-java-8-zoneddatetime-and-offsetdatetime

https://www.yiibai.com/javatime/javatime_zoneoffset.html

https://blog.csdn.net/hspingcc/article/details/73332252


最近发现一篇写的很好的文章:

LocalDateTime、OffsetDateTime、ZonedDateTime互转,这一篇绝对喂饱你

这里摘抄里面一段总结:

OffsetDateTime和ZonedDateTime的区别

LocalDateTime、OffsetDateTime、ZonedDateTime这三个哥们,LocalDateTime好理解,一般都没有异议。但是很多同学对OffsetDateTime和ZonedDateTime傻傻分不清,这里说说它俩的区别。

  1. OffsetDateTime = LocalDateTime + 偏移量ZoneOffset;ZonedDateTime = LocalDateTime + 时区ZoneId
  2. OffsetDateTime可以随意设置偏移值,但ZonedDateTime无法自由设置偏移值,因为此值是由时区ZoneId控制的
  3. OffsetDateTime无法支持夏令时等规则,但ZonedDateTime可以很好的处理夏令时调整
  4. OffsetDateTime得益于不变性一般用于数据库存储、网络通信;而ZonedDateTime得益于其时区特性,一般在指定时区里显示时间非常方便,无需认为干预规则
  5. OffsetDateTime代表一个瞬时值,而ZonedDateTime的值是不稳定的,需要在某个瞬时根据当时的规则计算出来偏移量从而确定实际值

总的来说,OffsetDateTime和ZonedDateTime的区别主要在于ZoneOffset和ZoneId的区别。如果你只是用来传递数据,请使用OffsetDateTime,若你想在特定时区里做时间显示那么请务必使用ZonedDateTime。

这篇关于Java8学习笔记:LocalDateTime、Instant 和 OffsetDateTime 相互转换的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1112118

相关文章

HarmonyOS学习(七)——UI(五)常用布局总结

自适应布局 1.1、线性布局(LinearLayout) 通过线性容器Row和Column实现线性布局。Column容器内的子组件按照垂直方向排列,Row组件中的子组件按照水平方向排列。 属性说明space通过space参数设置主轴上子组件的间距,达到各子组件在排列上的等间距效果alignItems设置子组件在交叉轴上的对齐方式,且在各类尺寸屏幕上表现一致,其中交叉轴为垂直时,取值为Vert

Ilya-AI分享的他在OpenAI学习到的15个提示工程技巧

Ilya(不是本人,claude AI)在社交媒体上分享了他在OpenAI学习到的15个Prompt撰写技巧。 以下是详细的内容: 提示精确化:在编写提示时,力求表达清晰准确。清楚地阐述任务需求和概念定义至关重要。例:不用"分析文本",而用"判断这段话的情感倾向:积极、消极还是中性"。 快速迭代:善于快速连续调整提示。熟练的提示工程师能够灵活地进行多轮优化。例:从"总结文章"到"用

JVM 的类初始化机制

前言 当你在 Java 程序中new对象时,有没有考虑过 JVM 是如何把静态的字节码(byte code)转化为运行时对象的呢,这个问题看似简单,但清楚的同学相信也不会太多,这篇文章首先介绍 JVM 类初始化的机制,然后给出几个易出错的实例来分析,帮助大家更好理解这个知识点。 JVM 将字节码转化为运行时对象分为三个阶段,分别是:loading 、Linking、initialization

Spring Security 基于表达式的权限控制

前言 spring security 3.0已经可以使用spring el表达式来控制授权,允许在表达式中使用复杂的布尔逻辑来控制访问的权限。 常见的表达式 Spring Security可用表达式对象的基类是SecurityExpressionRoot。 表达式描述hasRole([role])用户拥有制定的角色时返回true (Spring security默认会带有ROLE_前缀),去

浅析Spring Security认证过程

类图 为了方便理解Spring Security认证流程,特意画了如下的类图,包含相关的核心认证类 概述 核心验证器 AuthenticationManager 该对象提供了认证方法的入口,接收一个Authentiaton对象作为参数; public interface AuthenticationManager {Authentication authenticate(Authenti

Spring Security--Architecture Overview

1 核心组件 这一节主要介绍一些在Spring Security中常见且核心的Java类,它们之间的依赖,构建起了整个框架。想要理解整个架构,最起码得对这些类眼熟。 1.1 SecurityContextHolder SecurityContextHolder用于存储安全上下文(security context)的信息。当前操作的用户是谁,该用户是否已经被认证,他拥有哪些角色权限…这些都被保

Spring Security基于数据库验证流程详解

Spring Security 校验流程图 相关解释说明(认真看哦) AbstractAuthenticationProcessingFilter 抽象类 /*** 调用 #requiresAuthentication(HttpServletRequest, HttpServletResponse) 决定是否需要进行验证操作。* 如果需要验证,则会调用 #attemptAuthentica

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

Java架构师知识体认识

源码分析 常用设计模式 Proxy代理模式Factory工厂模式Singleton单例模式Delegate委派模式Strategy策略模式Prototype原型模式Template模板模式 Spring5 beans 接口实例化代理Bean操作 Context Ioc容器设计原理及高级特性Aop设计原理Factorybean与Beanfactory Transaction 声明式事物

【前端学习】AntV G6-08 深入图形与图形分组、自定义节点、节点动画(下)

【课程链接】 AntV G6:深入图形与图形分组、自定义节点、节点动画(下)_哔哩哔哩_bilibili 本章十吾老师讲解了一个复杂的自定义节点中,应该怎样去计算和绘制图形,如何给一个图形制作不间断的动画,以及在鼠标事件之后产生动画。(有点难,需要好好理解) <!DOCTYPE html><html><head><meta charset="UTF-8"><title>06