如何在Java 8中将LocalDateTime转换为Date [英] How convert LocalDateTime to Date in Java 8

查看:141
本文介绍了如何在Java 8中将LocalDateTime转换为Date的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我默认使用时区巴西,但是当抓到一个纽约的LocalDateTime并转换为 java.tim.Instant 时,即时会被正确填充。问题是当我尝试使用 Date.from(instantValue)生成日期,而不是生成纽约的日期时,我最终从巴西获得当前日期。

I'm using timezone Brazil by default, but when caught one LocalDateTime of New York and convert to java.tim.Instant the instant is filled correctly. The problem is when I try to generate a Date with Date.from (instantValue), instead of being generated a date of New York, I end up getting the current date from Brazil.

ZoneId nyZone = ZoneId.of("America/New_York");
ZoneId brazilZone = ZoneId.of("America/Recife");

LocalDateTime ldtBrazil = LocalDateTime.now(brazilZone);
LocalDateTime ldtNY = LocalDateTime.now(nyZone);

Instant instantBrazil = ldtBrazil.toInstant(ZoneOffset.UTC);
Instant instantNY = ldtNY.toInstant(ZoneOffset.UTC);

System.out.println("-------LocalDateTime-------");
System.out.println("ldtBrazil    : "+ldtBrazil);
System.out.println("ldtNY        : "+ldtNY);

System.out.println("\n-------Instant-------");
System.out.println("instantBrazil: "+instantBrazil);
System.out.println("instantNY    : "+instantNY);

long milliBrazil = instantBrazil.toEpochMilli();
long milliNY = instantNY.toEpochMilli();

System.out.println("\n----------Milli----------");
System.out.println("miliBrazil : "+milliBrazil);
System.out.println("miliNY     : "+milliNY);

Date dateBrazil = Date.from(instantBrazil);
Date dateNY = Date.from(instantNY);

System.out.println("\n---------Date From Instant---------");
System.out.println("dateBrazil: "+dateBrazil);
System.out.println("dateNY    : "+dateNY);

System.out.println("\n---------Date From Milli---------");
System.out.println("dateBrazil: "+new Date(milliBrazil));
System.out.println("dateNY    : "+new Date(milliNY));

结果

-------LocalDateTime-------
ldtBrazil    : 2016-09-21T22:11:52.118
ldtNY        : 2016-09-21T21:11:52.118

-------Instant-------
instantBrazil: 2016-09-21T22:11:52.118Z
instantNY    : 2016-09-21T21:11:52.118Z

----------Milli----------
miliBrazil : 1474495912118
miliNY     : 1474492312118

---------Date From Instant---------
dateBrazil: Wed Sep 21 19:11:52 BRT 2016
dateNY    : Wed Sep 21 18:11:52 BRT 2016 //this data must be related to   NY LocalDateTime, but reiceved a same date of Brazil.

---------Date From Milli---------
dateBrazil: Wed Sep 21 19:11:52 BRT 2016
dateNY    : Wed Sep 21 18:11:52 BRT 2016


推荐答案

LocalDateTime 表示没有区域



您似乎误解了 LocalDateTime

LocalDateTime means no zone

You seem to misunderstand the purpose of LocalDateTime.

此课程没有时区,没有偏离UTC 时间轴上的一个点。相反,它代表了一个关于可能时刻的模糊概念。名称Local ...可能违反直觉,因为它代表任何特定的地点,而是任何地点。

This class has no time zone and no offset-from-UTC. It is not a point on the timeline. Rather it represents a vague idea about possible moments. The name "Local…" may be counter-intuitive as it does not represent any particular locality, but rather any locality.

例如,今年圣诞节是2016年12月25日午夜,或 2016-12-25T00:00 。这是没有意义的,除非您在新西兰奥克兰或加尔各答IN或巴黎FR或蒙特利尔加利福尼亚州申请圣诞节,每个时间轴都是时间轴上的不同点,随后越往西方。

For example, Christmas this year is midnight at start of December 25, 2016, or 2016-12-25T00:00. This has no meaning until you apply a time zone to get Christmas in Auckland NZ or Kolkata IN or Paris FR or Montréal CA, each being a different point on the timeline, getting later and later as you go westward.

切勿使用 LocalDateTime ,因为您认为这样可以省去区域和偏移的麻烦。恰恰相反,你会把自己挖进一个含糊不清的日期时间值的洞。

Never use LocalDateTime because you think it will save you the hassle of zones and offsets. Just the opposite, you’ll be digging yourself into a hole with ambiguous date-time values.

您的大多数业务逻辑,日志记录,数据存储和数据交换都应该在 UTC 。将UTC视为一个真实的时间;所有其他区域和偏移都伪装成打扮的UTC值。

Most of your business logic, logging, data storage, and data exchange should all be in UTC. Think of UTC as the one true time; all the other zones and offsets are masquerading as dressed-up UTC values.

在java.time中,这意味着 Instant class是你的首选类,是日期时间对象的基本构建块。 Instant 类代表 UTC 中时间轴上的一个时刻,其分辨率为纳秒

In java.time, that means the Instant class is your go-to class, the basic building-blocks of date-time objects. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds.

Instant now = Instant.now();



ZonedDateTime



仅在需要访问挂钟时间时调整时区某些地区。应用 ZoneId 获取 ZonedDateTime 对象。

ZonedDateTime

Adjust into time zones only where required to access the wall-clock time of some region. Apply a ZoneId to get a ZonedDateTime object.

ZoneId zNewYork = ZoneId.of("America/New_York");
ZoneId zRecife = ZoneId.of("America/Recife");

ZonedDateTime zdtNewYork = now.atZone( zNewYork );
ZonedDateTime zdtRecife = now.atZone( zRecife );

所有这三个对象,现在 zdtNewYork zdtRecife 所有片刻,同时点上时间表。这三个人共享同一个时代。唯一的区别是我们看到他们的挂钟时间的镜头。

All three of these objects, now, zdtNewYork, and zdtRecife, are all the very some moment, the same simultaneous point on the timeline. All three share the same count-from-epoch. The only difference is the lens through which we see their wall-clock time.

避免使用与最早版本的Java捆绑在一起的麻烦的旧日期时间类。因此,请避免 java.util.Date java.util.Calendar 。他们真的那么糟糕。坚持使用java.time类。

Avoid using the troublesome old date-time classes bundled with the earliest versions of Java. So, avoid java.util.Date and java.util.Calendar. They really are that bad. Stick with java.time classes.

如果必须与尚未针对java.time类型更新的旧代码进行交互,则可以转换为/来自java.time类型。寻找添加到旧类的新方法。 java.util.Date.from 方法需要 Instant 。我们可以从 ZoneDateTime (或从 OffsetDateTime Instant >)。

If you must interact with old code not yet updated for java.time types, you can convert to/from java.time types. Look for new methods added to the old classes. The java.util.Date.from method takes an Instant. We can extract an Instant from a ZoneDateTime (or from OffsetDateTime).

java.util.Date utilDate = java.util.Date.from( zdtNewYork.toInstant() );

向另一个方向发展。

Instant instant = utilDate.toInstant();

有关转换的更多信息,请参阅我对该问题的回答将java.util.Date转换为java.time类型?

For more info on converting, see my Answer to the Question, Convert java.util.Date to what "java.time" type?

避免使用count-from-epoch数字例如1970年以来的UTC开始时的毫秒数。计数有多种粒度(毫秒,微秒,纳秒,整秒等)。除了1970年以外,各种计算机系统至少使用了十几个时代。这些数字在人类阅读时没有任何意义,因此可能无法检测到错误。

Avoid using the count-from-epoch numbers such as milliseconds-since-start-of-1970-in-UTC. There are various granularities used for the count (milliseconds, microseconds, nanoseconds, whole seconds, and more). There are at least a couple dozen epochs in use by various computer systems besides 1970. The numbers have no meaning when read by humans, so bugs may go undetected.

练习时,您可能会觉得它们很有用。在 Instant 上拨打 getEpochSecond getNano ,或截断值调用 toEpochMilli

You might find them useful when practicing. Call getEpochSecond and getNano on Instant, or for a truncated value call toEpochMilli.

java.time 框架内置于Java 8及更高版本中。这些类取代了麻烦的旧遗留日期时间类,例如 java.util.Date 日历 ,& SimpleDateFormat

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

Joda-Time 项目,现已进入维护模式 ,建议迁移到 java.time classes。

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

要了解更多信息,请参阅 Oracle Tutorial 。并搜索Stack Overflow以获取许多示例和解释。规范是 JSR 310

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

您可以直接与数据库交换 java.time 对象。使用符合 JDBC驱动程序 / jeps / 170rel =nofollow noreferrer> JDBC 4.2 或更高版本。不需要字符串,不需要 java.sql。* 类。

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

从哪里获取java.time班?

Where to obtain the java.time classes?


  • Java SE 8 Java SE 9 Java SE 10 Java SE 11 及更高版本 - 部分带有捆绑实现的标准Java API。


    • Java 9增加了一些小功能和修复。

    • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
      • Java 9 adds some minor features and fixes.
      • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
      • Later versions of Android bundle implementations of the java.time classes.
      • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

      ThreeTen-Extra 项目使用其他类扩展java.time。该项目是未来可能添加到java.time的试验场。您可以在这里找到一些有用的课程,例如 Interval YearWeek YearQuarter 更多

      这篇关于如何在Java 8中将LocalDateTime转换为Date的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆