LocalDate 到 java.util.Date 反之亦然最简单的转换?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33066904/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
LocalDate to java.util.Date and vice versa simplest conversion?
提问by George
Is there a simple way to convert a LocalDate
(introduced with Java 8) to java.util.Date
object?
有没有一种简单的方法可以将 a LocalDate
(Java 8 引入)转换为java.util.Date
对象?
By 'simple', I mean simpler than this:
通过“简单”,我的意思是比这更简单:
Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
which seems a bit awkward to me.
这对我来说似乎有点尴尬。
Since we are interested only in the date portion and there is no timezone information in neither of the objects, why introduce time zones explicitly? The midnight time and the system default timezone should be taken implicitly for the conversion.
既然我们只对日期部分感兴趣,而两个对象中都没有时区信息,为什么要明确引入时区呢?转换时应隐式采用午夜时间和系统默认时区。
采纳答案by George
Actually there is. There is a static method valueOfin the java.sql.Date
object which does exactly that. So we have
实际上有。有一个静态方法的valueOf在java.sql.Date
这不正是那个对象。所以我们有
java.util.Date date = java.sql.Date.valueOf(localDate);
and that's it. No explicit setting of time zones because the local time zone is taken implicitly.
就是这样。没有明确设置时区,因为本地时区是隐式的。
From docs:
从文档:
The provided LocalDate is interpreted as the local date in the local time zone.
提供的 LocalDate 被解释为本地时区中的本地日期。
The java.sql.Date
subclasses java.util.Date
so the result is a java.util.Date
also.
该java.sql.Date
子类java.util.Date
这样的结果是java.util.Date
也。
And for the reverse operation there is a toLocalDatemethod in the java.sql.Date class. So we have:
对于反向操作,java.sql.Date 类中有一个toLocalDate方法。所以我们有:
LocalDate ld = new java.sql.Date(date.getTime()).toLocalDate();
LocalDate ld = new java.sql.Date(date.getTime()).toLocalDate();
回答by msvetterracer93
You can convert the java.util.Date
object into a String
object, which will format the date as yyyy-mm-dd.
您可以将java.util.Date
对象转换为String
对象,该对象会将日期格式化为 yyyy-mm-dd。
LocalDate has a parse
method that will convert it to a LocalDate
object. The string must represent a valid date and is parsed using DateTimeFormatter.ISO_LOCAL_DATE.
LocalDate 有一个parse
方法可以将它转换为一个LocalDate
对象。该字符串必须表示有效日期,并使用 DateTimeFormatter.ISO_LOCAL_DATE 进行解析。
Date to LocalDate
日期到本地日期
LocalDate.parse(Date.toString())
回答by Basil Bourque
tl;dr
tl;博士
Is there a simple way to convert a LocalDate (introduced with Java 8) to java.util.Date object? By 'simple', I mean simpler than this
有没有一种简单的方法可以将 LocalDate(在 Java 8 中引入)转换为 java.util.Date 对象?通过“简单”,我的意思是比这更简单
Nope. You did it properly, and as concisely as possible.
不。你做得对,而且尽可能简洁。
java.util.Date.from( // Convert from modern java.time class to troublesome old legacy class. DO NOT DO THIS unless you must, to inter operate with old code not yet updated for java.time.
myLocalDate // `LocalDate` class represents a date-only, without time-of-day and without time zone nor offset-from-UTC.
.atStartOfDay( // Let java.time determine the first moment of the day on that date in that zone. Never assume the day starts at 00:00:00.
ZoneId.of( "America/Montreal" ) // Specify time zone using proper name in `continent/region` format, never 3-4 letter pseudo-zones such as “PST”, “CST”, “IST”.
) // Produce a `ZonedDateTime` object.
.toInstant() // Extract an `Instant` object, a moment always in UTC.
)
Read below for issues, and then think about it. How could it be simpler? If you ask me what time does a date start, how else could I respond but ask you “Where?”?. A new day dawns earlier in Paris FR than in Montréal CA, and still earlier in Kolkata IN, and even earlier in Auckland NZ, all different moments.
阅读下面的问题,然后思考。怎么可能更简单?如果你问我约会从几点开始,除了问你“在哪里?”之外,我还能怎么回答?新的一天在法国巴黎比在加拿大蒙特利尔更早,在加尔各答更早,在新西兰奥克兰更早,所有不同的时刻。
So in converting a date-only (LocalDate
) to a date-time we mustapply a time zone (ZoneId
) to get a zoned value (ZonedDateTime
), and then move into UTC (Instant
) to match the definition of a java.util.Date
.
因此,在将仅日期 ( LocalDate
) 转换为日期时间时,我们必须应用时区 ( ZoneId
) 以获取分区值 ( ZonedDateTime
),然后移动到 UTC ( Instant
) 以匹配 a 的定义java.util.Date
。
Details
细节
Firstly, avoid the old legacy date-time classes such as java.util.Date
whenever possible. They are poorly designed, confusing, and troublesome. They were supplanted by the java.time classes for a reason, actually, for manyreasons.
首先,java.util.Date
尽可能避免旧的遗留日期时间类。它们设计不佳,令人困惑且麻烦。它们被 java.time 类取代是有原因的,实际上,有很多原因。
But if you must, you can convert to/from java.time types to the old. Look for new conversion methods added to the old classes.
但如果必须,您可以将 java.time 类型转换为/从 java.time 类型转换为旧类型。寻找添加到旧类的新转换方法。
java.util.Date
→ java.time.LocalDate
java.util.Date
→ java.time.LocalDate
Keep in mind that a java.util.Date
is a misnomer as it represents a date plusa time-of-day, in UTC. In contrast, the LocalDate
class represents a date-only value without time-of-day and without time zone.
请记住,ajava.util.Date
是用词不当,因为它代表了一个日期加上一个 UTC 时间。相比之下,LocalDate
该类表示没有时间和时区的仅日期值。
Going from java.util.Date
to java.time means converting to the equivalent class of java.time.Instant
. The Instant
class represents a moment on the timeline in UTCwith a resolution of nanoseconds(up to nine (9) digits of a decimal fraction).
从java.util.Date
到 java.time 意味着转换为java.time.Instant
. 该Instant
级表示时间轴上的时刻UTC,分辨率为纳秒(最多小数的9个位数)。
Instant instant = myUtilDate.toInstant();
The LocalDate
class represents a date-only value without time-of-day and without time zone.
该LocalDate
级表示没有时间一天和不同时区的日期,唯一的价值。
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris Franceis a new day while still “yesterday” in Montréal Québec.
时区对于确定日期至关重要。对于任何给定时刻,日期因地区而异。例如,在法国巴黎午夜过后几分钟是新的一天,而在魁北克蒙特利尔仍然是“昨天” 。
So we need to move that Instant
into a time zone. We apply ZoneId
to get a ZonedDateTime
.
所以我们需要把它Instant
移到一个时区。我们申请ZoneId
获得一个ZonedDateTime
.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
From there, ask for a date-only, a LocalDate
.
从那里,要求一个仅限日期的LocalDate
.
LocalDate ld = zdt.toLocalDate();
java.time.LocalDate
→ java.util.Date
java.time.LocalDate
→ java.util.Date
To move the other direction, from a java.time.LocalDate
to a java.util.Date
means we are going from a date-only to a date-time. So we must specify a time-of-day. You probably want to go for the first moment of the day. Do notassume that is 00:00:00
. Anomalies such as Daylight Saving Time (DST) means the first moment may be another time such as 01:00:00
. Let java.time determine that value by calling atStartOfDay
on the LocalDate
.
向另一个方向移动,从 ajava.time.LocalDate
到 ajava.util.Date
意味着我们将从仅日期到日期时间。所以我们必须指定一个时间。你可能想在一天的第一刻去。难道不认为是00:00:00
。夏令时 (DST) 等异常意味着第一个时刻可能是另一个时间,例如01:00:00
。让java.time通过调用确定的值atStartOfDay
上LocalDate
。
ZonedDateTime zdt = myLocalDate.atStartOfDay( z );
Now extract an Instant
.
现在提取一个Instant
.
Instant instant = zdt.toInstant();
Convert that Instant
to java.util.Date
by calling from( Instant )
.
通过调用将其转换Instant
为.java.util.Date
from( Instant )
java.util.Date d = java.util.Date.from( instant );
More info
更多信息
- Oracle Tutorial
- Similar Question, Convert java.util.Date to what “java.time” type?
About java.time
关于java.time
The java.timeframework is built into Java 8 and later. These classes supplant the troublesome old legacydate-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
该java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date
, Calendar
, & SimpleDateFormat
。
The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.
现在处于维护模式的Joda-Time项目建议迁移到java.time类。
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310。
You may exchange java.timeobjects directly with your database. Use a JDBC drivercompliant with JDBC 4.2or later. No need for strings, no need for java.sql.*
classes.
您可以直接与您的数据库交换java.time对象。使用符合JDBC 4.2或更高版本的JDBC 驱动程序。不需要字符串,不需要类。java.sql.*
Where to obtain the java.time classes?
从哪里获得 java.time 类?
- Java SE 8, Java SE 9, and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6and Java SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- Later versions of Android bundle implementations of the java.time classes.
- For earlier Android (<26), the ThreeTenABPproject adapts ThreeTen-Backport(mentioned above). See How to use ThreeTenABP….
- Java SE 8、Java SE 9及更高版本
- 内置。
- 具有捆绑实现的标准 Java API 的一部分。
- Java 9 添加了一些小功能和修复。
- Java SE 6和Java SE 7
- 多的java.time功能后移植到Java 6和7在ThreeTen-反向移植。
- 安卓
- java.time 类的更高版本的 Android 捆绑实现。
- 对于早期的 Android(<26),ThreeTenABP项目采用了ThreeTen-Backport(上面提到过)。请参阅如何使用ThreeTenABP ...。
The ThreeTen-Extraproject extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
该ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如Interval
,YearWeek
,YearQuarter
,和更多。
回答by estevamdf
I solved this question with solution below
我用下面的解决方案解决了这个问题
import org.joda.time.LocalDate;
Date myDate = new Date();
LocalDate localDate = LocalDate.fromDateFields(myDate);
System.out.println("My date using Date" Nov 18 11:23:33 BRST 2016);
System.out.println("My date using joda.time LocalTime" 2016-11-18);
In this case localDate print your date in this format "yyyy-MM-dd"
在这种情况下 localDate 以这种格式“yyyy-MM-dd”打印您的日期
回答by Hai Nguyen
Date -> LocalDate:
日期 -> 本地日期:
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate -> Date:
本地日期 -> 日期:
Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
回答by Simhadri
Converting LocalDateTime to java.util.Date
将 LocalDateTime 转换为 java.util.Date
LocalDateTime localDateTime = LocalDateTime.now();
ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneOffset.systemDefault());
Instant instant = zonedDateTime.toInstant();
Date date = Date.from(instant);
System.out.println("Result Date is : "+date);
回答by fjkjava
Date to LocalDate
日期到本地日期
Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate to Date
本地日期至今
LocalDate localDate = LocalDate.now();
Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());