Java 中未弃用的 Date(String s) 的完全等价物?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/657962/
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
A non-deprecated exact equivalent of Date(String s) in Java?
提问by itsadok
I have old code that uses new Date(dateString)
to parse a date string. Compiling the code produces the deprecation warning Date(java.lang.String) in java.util.Date has been deprecated
.
我有new Date(dateString)
用于解析日期字符串的旧代码。编译代码会产生弃用警告Date(java.lang.String) in java.util.Date has been deprecated
。
The javadoc unhelpfully advises me to use DateFormat.parse()
, even though the DateFormat
class does not have a static parse
method.
javadoc 无益地建议我使用DateFormat.parse()
,即使DateFormat
该类没有静态parse
方法。
Now, I know how to use SimpleDateFormat
, but I want to make sure I'm getting the exact same behaviourof the deperecated Date
constructor.
现在,我知道如何使用SimpleDateFormat
,但我想确保我得到了与废弃Date
构造函数完全相同的行为。
采纳答案by itsadok
Here's my guess (I posted as community wiki so you can vote up if I'm right):
这是我的猜测(我作为社区维基发布,所以如果我是对的,你可以投票):
Date parsed;
try {
SimpleDateFormat format =
new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
parsed = format.parse(dateString);
}
catch(ParseException pe) {
throw new IllegalArgumentException(pe);
}
回答by Can Berk Güder
DateFormat has static methods that return DateFormat instances. I don't know which one (if any) has the same behavior as Date(String s)
but here you go:
DateFormat 具有返回 DateFormat 实例的静态方法。我不知道哪一个(如果有的话)有相同的行为,Date(String s)
但是你去吧:
DateFormat.getInstance()
DateFormat.getDateInstance()
DateFormat.getTimeInstance()
DateFormat.getDateTimeInstance()
回答by Nicolas
Short answer (before further investigation) is: no, it is not equivalent. the Date(String toParse) constructor is equivalent to the parse method of the class Date (which is also deprecated)... And the javadocof this method claims:
简短的回答(在进一步调查之前)是:不,它不等价。Date(String toParse) 构造函数等价于类 Date 的 parse 方法(它也已弃用)......并且该方法的javadoc声称:
Note that this is slightly different from the interpretation of years less than 100 that is used in SimpleDateFormat.
请注意,这与 SimpleDateFormat 中使用的小于 100 年的解释略有不同。
If it is the only change, I guess you can go on this way.
如果这是唯一的变化,我想你可以这样走下去。
回答by Brian Agnew
SimpleDateFormat is the way to go. Can I point out, however, that you may feel compelled to define one SimpleDateFormat instance and build Date objects using this. If you do, beware that SimpleDateFormat is not thread-safe and you may be exposing yourself to some potentially hard-to-debug issues!
SimpleDateFormat 是要走的路。但是,我能否指出,您可能不得不定义一个 SimpleDateFormat 实例并使用它构建 Date 对象。如果这样做,请注意 SimpleDateFormat 不是线程安全的,并且您可能会将自己暴露在一些潜在的难以调试的问题中!
I'd recommend taking this opportunity to look at Jodawhich is a much better thought-out (and thread-safe) API. It forms the basis of JSR-310, which is the new proposed Java Date API.
我建议借此机会看看Joda,它是一个经过深思熟虑的(和线程安全的)API。它构成了 JSR-310 的基础,JSR-310 是新提出的 Java Date API。
I understand this is a bit more work. However it's probably worthwhile given that you're having to refactor code at the moment.
我知道这需要更多的工作。然而,鉴于您目前必须重构代码,这可能是值得的。
回答by Marty Lamb
If you take a look at source of the Date.parse(String s) method that Nicolas mentions, you'll see that it will be difficult or impossible to construct a date format that exactlyreproduces the behavior.
如果您查看 Nicolas 提到的 Date.parse(String s) 方法的来源,您会发现构建完全重现行为的日期格式将是困难的或不可能的。
If you just want to eliminate the warning, you could put @SuppressWarnings({“deprecation”})
outside the method calling the Date(String) constructor.
如果您只想消除警告,您可以将@SuppressWarnings({“deprecation”})
调用 Date(String) 构造函数的方法放在外面。
If you really want to ensure future access to this behavior with future JREs, you might be able to just extract the method from the JDK sources and put it into your own sources. This would require a careful read of the source code licenses and consideration of their application to your specific project, and might not be permissible at all.
如果您真的想确保将来使用 JRE 来访问此行为,您可以只从 JDK 源中提取该方法并将其放入您自己的源中。这需要仔细阅读源代码许可证并考虑它们在您的特定项目中的应用,并且可能根本不允许。
回答by user1237092
To parse a date time string in ISO format you should use the DateFormat like this:
要解析 ISO 格式的日期时间字符串,您应该像这样使用 DateFormat:
java.text.DateFormat.getDateInstance().parse(dt);
java.text.DateFormat.getDateInstance().parse(dt);
With SimpleDateFormat you need to know the format.
使用 SimpleDateFormat 您需要知道格式。
回答by Basil Bourque
tl;dr
tl;博士
ZonedDateTime.format(
input ,
DateTimeFormatter.ofPattern(
"EEE MMM dd HH:mm:ss zzz uuuu" ,
Locale.ENGLISH
)
)
java.time
时间
The terrible Date
and DateFormat
classes were supplanted years ago by the modern java.timeclasses with the adoption of JSR 310.
多年前,随着JSR 310的采用,可怕的Date
和DateFormat
类被现代java.time类所取代。
The constructor you referenceis actually calls on the static method Date.parse
. As that documentation explains, that method takes a variety of formats. There is single point for the same behavior in java.time. However, I would doubt your app is encountering all those various format syntaxes simultaneously.
您引用的构造函数实际上是对静态方法的调用Date.parse
。正如该文档所解释的那样,该方法采用多种格式。java.time 中有相同行为的单点。但是,我怀疑您的应用程序是否同时遇到了所有这些不同的格式语法。
I suggest you look at the specific formats used by your actual data. Then craft a collection of DateTimeFormatter
objects to match. Note that unlike the legacy classes, the java.timeclasses are entirely thread-safe. So you can keep one set of formatters around for use repeatedly throughout your app and across threads.
我建议您查看实际数据使用的特定格式。然后制作一组DateTimeFormatter
要匹配的对象。请注意,与遗留类不同,java.time类是完全线程安全的。因此,您可以保留一组格式化程序,以便在整个应用程序和线程中重复使用。
For the formatting pattern shown in the accepted Answer, here is the equivalent in java.timeusing the DateTimeFormatter
class. Note that you should explicitly state your desired/expected locale rather than rely implicitly on the JVM's current default locale.
对于接受的答案中显示的格式化模式,这里是java.time 中使用DateTimeFormatter
该类的等效项。请注意,您应该明确说明您想要/期望的语言环境,而不是隐式依赖 JVM 的当前默认语言环境。
DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM dd HH:mm:ss zzz uuuu" , Locale.ENGLISH ) ;
ZonedDateTime zdt = ZonedDateTime.format( input , f ) ;
You should avoid using the legacy date-time classes such as java.util.Date
wherever possible. But if you must have a Date
to interoperate with old code not yet updated to java.time, you can convert. Look to new conversions methods added to the old classes.
您应该尽可能避免使用旧的日期时间类java.util.Date
。但是,如果您必须有一个Date
与尚未更新为java.time 的旧代码进行互操作,则可以进行转换。查看添加到旧类的新转换方法。
The misnamed java.util.Date
represents a moment in UTC. Its modern equivalent
is the java.time.Instant
class. We can extract an Instant
from our ZonedDateTime
. Then convert to a Date
.
错误的名字java.util.Date
代表了UTC中的一个时刻。它的现代等价物是java.time.Instant
类。我们可以Instant
从我们的ZonedDateTime
. 然后转换为Date
.
Instant instant = zdt.toInstant() ; // Adjust from time zone to UTC.
java.util.Date d = Date.from( instant ) ; // Convert from modern class `Instant` to legacy class `Date`.
Going the other direction.
走向另一个方向。
Instant instant = d.toInstant() ; // Convert from legacy class `Date` to modern class `Instant`.
ZonedDateTime zdt = instant.atZone( ZoneId.of( "Pacific/Auckland" ) ) ; // Adjust from UTC to the wall-clock time used by the people of a particular region (a time zone).
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
。
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。
The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.
现在处于维护模式的Joda-Time项目建议迁移到java.time类。
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, 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.
- Java SE 6and Java SE 7
- Most of the java.timefunctionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- Later versions of Android bundle implementations of the java.timeclasses.
- For earlier Android (<26), the ThreeTenABPproject adapts ThreeTen-Backport(mentioned above). See How to use ThreeTenABP….
- Java SE 8、Java SE 9、Java SE 10、Java SE 11及更高版本 - 标准 Java API 的一部分,具有捆绑实现。
- Java 9 添加了一些小功能和修复。
- Java SE 6和Java SE 7
- 大部分java.time功能在ThreeTen-Backport中向后移植到 Java 6 & 7 。
- 安卓
- 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
,和更多。