Java 有没有好的日期解析器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/222245/
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
Is there a good date parser for Java?
提问by Horcrux7
Does anyone know a good date parser for different languages/locales. The built-in parser of Java (SimpleDateFormat) is very strict. It should complete missing parts with the current date.
有谁知道适用于不同语言/语言环境的良好日期解析器。Java 内置的解析器(SimpleDateFormat)非常严格。它应该用当前日期完成缺失的部分。
For example
例如
- if I do not enter the year (only day and month) then the current year should be used.
- if the year is 08 then it should not parse 0008 because the current year pattern has 4 digits.
- 如果我不输入年份(仅日和月),则应使用当前年份。
- 如果年份是 08 那么它不应该解析 0008 因为当前年份模式有 4 位数字。
Edit: I want to parse the input from a user. For example if the locale date format of the user is "dd.mm.yyyy" and the user type only "12.11." then the parser should accept this as a valid date with the value "12.11.2008". The target is a good usability.
编辑:我想解析来自用户的输入。例如,如果用户的语言环境日期格式是“dd.mm.yyyy”并且用户只输入“12.11”。那么解析器应该接受这个值为“12.11.2008”的有效日期。目标是良好的可用性。
回答by Petteri Hietavirta
Check Joda Time, and its Freaky Formatters.
检查 Joda Time 及其奇怪的格式化程序。
Java 8 includes JSR-310so that could be a solution as well.
Java 8 包含 JSR-310,因此它也可能是一个解决方案。
回答by Joe Liversedge
回答by Jon Skeet
(Edited for clarity.)
(为清楚起见进行了编辑。)
Personally, I think strict is good. So many different situations call for different rules around relaxed parsing, it's impossible to really put that into a common library comprehensively.
我个人认为严格是好的。这么多不同的情况需要围绕宽松解析的不同规则,因此不可能真正将其全面地放入一个公共库中。
However, I wouldthoroughly recommend Joda Timeinstead of the built-in date/time classes in general. Their formatters and parsers are thread-safe and immutable, which helps too. Joda Time has some support for relaxed parsing, as shown in the other answer, but you should expect to have to provide some of the rules yourself.
但是,我会彻底推荐Joda Time而不是一般的内置日期/时间类。它们的格式化程序和解析器是线程安全且不可变的,这也有帮助。Joda Time 支持轻松解析,如另一个答案所示,但您应该期望自己提供一些规则。
回答by madlep
回答by Basil Bourque
tl;dr
tl;博士
java.time.format.DateTimeFormatterBuilder::parseDefaulting
java.time.format.DateTimeFormatterBuilder::parseDefaulting
java.time
时间
The DateTimeFormatterclass parses strings into date-time objects.
在DateTimeFormatter类解析字符串到日期时间对象。
You can create customized instances of DateTimeFormatterby using the DateTimeFormatterBuilderclass. That builder class enables you to specify default values for missing components of the input string.
您可以DateTimeFormatter使用DateTimeFormatterBuilder该类创建 的自定义实例。该构建器类使您能够为输入字符串的缺失组件指定默认值。
DateTimeFormatter f =
new DateTimeFormatterBuilder()
.appendPattern( "MM-dd" )
.parseDefaulting(
ChronoField.YEAR ,
ZonedDateTime.now( ZoneId.of( "America/Montreal" ) ).getYear()
)
.toFormatter() ;
String input = "01-23" ;
LocalDate ld = LocalDate.parse( input , f ) ;
System.out.println( ld ) ;
ld.toString(): 2018-01-23
ld.toString(): 2018-01-23
See also DateTimeFormatterBuilder with specified parseDefaulting conflicts for YEAR field.
另请参阅DateTimeFormatterBuilder 与 YEAR 字段的指定 parseDefaulting 冲突。
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, Java SE 10, 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 SE 10及更高版本
- 内置。
- 具有捆绑实现的标准 Java API 的一部分。
- Java 9 添加了一些小功能和修复。
- Java SE 6和Java SE 7
- 多的java.time功能后移植到Java 6和7在ThreeTen-反向移植。
- 安卓
- 更高版本的 Android 捆绑实现 java.time 类。
- 对于早期的 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 Basil Bourque
The POJava project on SourceForge has a DateTime object that parses dates from multiple languages (when month is specified as a name) and is configurable between MM-DD-YYYY and DD-MM-YYYY. It parses dates heuristically, picking out the most likely year, month, date, hour, minute, second, and time zone rather than supporting predefined formats. The jar file is about 60K in size.
SourceForge 上的 POJava 项目有一个 DateTime 对象,它可以解析多种语言的日期(当月份被指定为名称时),并且可以在 MM-DD-YYYY 和 DD-MM-YYYY 之间进行配置。它启发式地解析日期,挑选出最可能的年、月、日、时、分、秒和时区,而不是支持预定义的格式。jar 文件大小约为 60K。
There is ambiguity in interpretation of a date like "10-08" in that it could be intended as shorthand for either "2008-10-08" or "Oct 2008". You could append the year yourself if you are accepting the sort of shorthand you give in your example.
对诸如“10-08”之类的日期的解释存在歧义,因为它可能被用作“2008-10-08”或“2008 年 10 月”的简写。如果您接受您在示例中给出的那种速记,您可以自己附加年份。
Proj: POJavaDocs: HOWTO use DateTime
项目:POJava文档:如何使用 DateTime
回答by dfa
I tried to implement an extensible PHP's strtotimein Java in this answer
我试图在这个答案中用strtotimeJava实现一个可扩展的 PHP
回答by Ichorus
Use DateFormat ... Current standard until the welcome respite of Joda.
使用 DateFormat ... 当前标准,直到 Joda 的欢迎喘息。
回答by codeLes
Calendaris usually the way to go, but understand that most Java Date management will be handled on your part if you want it done properly. Timezoneis a good thing to look into if you have to manage international/cross-zone info. Joda Timeis also a neat thing and is the inspiration behind the new suggested Date/Time concepts to be added to Java in JSR 310.
日历通常是可行的方法,但请了解,如果您希望正确完成大多数 Java 日期管理,将由您自己处理。 如果您必须管理国际/跨区域信息,时区是一个很好的选择。Joda Time也是一个很好的东西,它是在JSR 310 中添加到 Java 的新建议日期/时间概念背后的灵感。
Hope this is helpful.
希望这是有帮助的。
回答by Joey Gibson
I would have to say +1 for JodaTime. In addition to parsing, Joda makes just about every date-related operation better.
我不得不为 JodaTime 说 +1。除了解析之外,Joda 使几乎所有与日期相关的操作都变得更好。

