简体   繁体   English

如何解析日期字符串,例如“ 21Jul12”

[英]How to parse the date string like '21Jul12'

How to parse the date string like '21Jul12'. 如何解析日期字符串,例如“ 21Jul12”。 I have tried the following way: 我尝试了以下方法:

import org.apache.commons.lang.time._

DateUtils.parseDate("21Jul12", Array("ddMMMyy"));

but it can't work due to the error: 但由于错误而无法使用:

java.text.ParseException: Unable to parse the date: 21Jul21
    at org.apache.commons.lang.time.DateUtils.parseDateWithLeniency(DateUtils.java:359)
    at org.apache.commons.lang.time.DateUtils.parseDate(DateUtils.java:285)
    at .<init>(<console>:20)
    at .<clinit>(<console>)
    at .<init>(<console>:11)
    at .<clinit>(<console>)
    at $print(<console>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at scala.tools.nsc.interpreter.IMain$ReadEvalPrint.call(IMain.scala:704)
    at scala.tools.nsc.interpreter.IMain$Request$$anonfun$14.apply(IMain.scala:920)
    at scala.tools.nsc.interpreter.Line$$anonfun$1.apply$mcV$sp(Line.scala:43)
    at scala.tools.nsc.io.package$$anon$2.run(package.scala:25)
    at java.lang.Thread.run(Thread.java:662)

Even I use java.text.SimpleDateFormat , i got a similiar exception: 即使我使用java.text.SimpleDateFormat ,我也有类似的异常:

java.text.ParseException: Unparseable date: "21Jul12"
    at java.text.DateFormat.parse(DateFormat.java:337)
    at .<init>(<console>:13)
    at .<clinit>(<console>)
    at .<init>(<console>:11)
    at .<clinit>(<console>)
    at $print(<console>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at scala.tools.nsc.interpreter.IMain$ReadEvalPrint.call(IMain.scala:704)
    at scala.tools.nsc.interpreter.IMain$Request$$anonfun$14.apply(IMain.scala:920)
    at scala.tools.nsc.interpreter.Line$$anonfun$1.apply$mcV$sp(Line.scala:43)
    at scala.tools.nsc.io.package$$anon$2.run(package.scala:25)
    at java.lang.Thread.run(Thread.java:662)

Here is the code for the above mentioned dates to parse 这是上述日期的解析代码

System.out.println("ddMMMyy >>>" + DateUtils.parseDate("21Jul12", new String[] { "ddMMMyy" }));

System.out.println("yyyy-MM-dd >>>" + DateUtils.parseDate("2012-07-21", new String[] { "yyyy-MM-dd" }));

System.out.println("yyyy MMM dd >>>" + DateUtils.parseDate("2012 Jul 21", new String[] { "yyyy MMM dd" }));

and the result on the console 并在控制台上显示结果

ddMMMyy >>>Sat Jul 21 00:00:00 CEST 2012
yyyy-MM-dd >>>Sat Jul 21 00:00:00 CEST 2012
yyyy MMM dd >>>Sat Jul 21 00:00:00 CEST 2012

maybe you tried to parse "2012 Jul 21" with "ddMMMyy" 也许您尝试使用“ ddMMMyy”解析“ 2012 Jul 21”

System.out.println("ddMMMyy >>>" + DateUtils.parseDate("2012 Jul 21", new String[] { "ddMMMyy" }));

gives your stack 给你的筹码

java.text.ParseException: Unable to parse the date: 2012 Jul 21
at org.apache.commons.lang.time.DateUtils.parseDateWithLeniency(DateUtils.java:359)
at org.apache.commons.lang.time.DateUtils.parseDate(DateUtils.java:285)
at com.collibra.dgc.core.model.activity.impl.TestTree.testname(TestTree.java:88)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

it works when I set the locale to Locale.en_US explicitly. 当我将语言环境明确设置为Locale.en_US时,它起作用。 Exception thrown because of the default locale setting is Locale.CHINA 由于默认语言环境设置为Locale.CHINA引发异常

We use a process of elimination for our date parsing, basically, we use an array of commonly used date formats (for our application) and the one that doesn't throw an exception is the one we use. 我们使用消除法进行日期解析,基本上,我们使用一系列常用的日期格式(对于我们的应用程序),并且不会引发异常的是我们使用的一种。 Not the cleanest of solutions, but it works... 不是最干净的解决方案,但它可以工作...

For example 例如

parse("2012 Jul 21", "ddMMMyy", "yyyy MMM dd");
parse("21Jul12", "ddMMMyy", "yyyy MMM dd");


public Date parse(String value, String... formats) throws ParseException {
    Date date = null;

    for (String format : formats) {
        try {
            date = new SimpleDateFormat(format).parse(value);
        } catch (ParseException exp) {
        }
    }

    if (date == null) {
        throw new ParseException(value + " is an unrecognized date format", 0);
    }

    return date;
}
String date="21JUL12";
        try {
            System.out.println(new   SimpleDateFormat("ddMMMyy").parse(date));
        }
        catch(ParseException ex) {
            ex.printStackTrace();
        }

the above code gives me this output: 上面的代码给了我这个输出:

Sat Jul 21 00:00:00 BST 2012

tl;dr TL;博士

LocalDate.parse(                                          // Represent a date-only value without time-of-day and without time zone using the `LocalDate` class.
    "21Jul12" ,                                           // A poor choice of format for date value as text. Instead use standard ISO 8601 formats.
    DateTimeFormatter.ofPattern( "ddMMMuu" , Locale.US )  // Specify `Locale` to determine the human language and cultural norms used in translating.
)

No need for Apache utilities. 无需Apache实用程序。

java.time java.time

The modern approach uses java.time classes. 现代方法使用java.time类。

String input = "21Jul12" ; 
DateTimeFormatter f = DateTimeFormatter.ofPattern( "ddMMMuu" , Locale.US ) ;
LocalDate ld = LocalDate.parse( input , f ) ;

ld.toString(): 2012-07-21 ld.toString():2012-07-21

Two tips: 两个提示:

  • Use 4-digit years. 使用4位数字的年份。
    • Saving the space of two digits is not worth the ambiguity, confusion, and errors I have seen spawned both among programmers and users/readers. 节省两位数的空间不值得在程序员和用户/阅读者之间产生歧义,混乱和错误。 Pixels and toner are cheap enough nowadays that I suspect you can afford the two extra digits for century. 如今,像素和碳粉已经足够便宜了,我怀疑您可以负担得起世纪的两位数数字。
    • In any event, the java.time classes assume 21st century ( 20xx ) if omitted. 无论如何,如果省略,则java.time类采用21世纪( 20xx )。
  • Use standard ISO 8601 formats for exchanging date-time values as text. 使用标准的ISO 8601格式将日期时间值交换为文本。
    • These formats are wisely designed to be unambiguous, easy to parse by machine, and easy to read by humans across various cultures. 明智地设计了这些格式,使其模棱两可,易于通过机器解析,并且易于跨各种文化的人们阅读。
    • The java.time classes use these standard formats by default when parsing/generating strings. 解析/生成字符串时, java.time类默认使用这些标准格式。

About java.time 关于java.time

The java.time framework is built into Java 8 and later. java.time框架内置于Java 8及更高版本中。 These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat . 这些类取代了麻烦的旧的旧式日期时间类,例如java.util.DateCalendarSimpleDateFormat

The Joda-Time project, now in maintenance mode , advises migration to the java.time classes. 现在处于维护模式Joda-Time项目建议迁移到java.time类。

To learn more, see the Oracle Tutorial . 要了解更多信息,请参见Oracle教程 And search Stack Overflow for many examples and explanations. 并在Stack Overflow中搜索许多示例和说明。 Specification is JSR 310 . 规格为JSR 310

Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. 使用兼容JDBC 4.2或更高版本的JDBC驱动程序 ,您可以直接与数据库交换java.time对象。 No need for strings nor java.sql.* classes. 不需要字符串或java.sql。*类。

Where to obtain the java.time classes? 在哪里获取java.time类?

The ThreeTen-Extra project extends java.time with additional classes. ThreeTen-Extra项目使用其他类扩展了java.time。 This project is a proving ground for possible future additions to java.time. 该项目为将来可能在java.time中添加内容提供了一个试验场。 You may find some useful classes here such as Interval , YearWeek , YearQuarter , and more . 您可以在这里找到一些有用的类,比如IntervalYearWeekYearQuarter ,和更多

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将字符串日期“2019-04-21T12:08:35”转换为 SimpleDateFormat,然后转换为日期? - How to convert a string date "2019-04-21T12:08:35" to SimpleDateFormat, there by convert to Date? 如何在 java 中将字符串 2020 年 7 月 21 日晚上 7:53:14 转换为“DD/MM/YYYY a”格式 - How to convert String Jul 21, 2020, 7:53:14 PM into “DD/MM/YYYY a” format in java SimpleDateFormat无法解析日期:使用解析方法时的“9-Jul” - SimpleDateFormat Unparseable date: “9-Jul” when using parse method 如何使用“Wed, 01 Jul 2015 17:32:41 EDT”解析字符串 - How to parser string to date with "Wed, 01 Jul 2015 17:32:41 EDT 如何解析包含格式“Oct 1, 2015 12:00:00 AM”的日期的字符串? - How to parse a string which holds date of format "Oct 1, 2015 12:00:00 AM"? 如何将这种格式的日期 (Tue Jul 13 00:00:00 CEST 2010) 转换为 Java 日期(字符串来自 alfresco 属性) - How to convert a date in this format (Tue Jul 13 00:00:00 CEST 2010) to a Java Date (The string comes from an alfresco property) 我怎样才能在java中获得日期格式“11, jul,Tue”? - How can i get the date formate "11, jul,Tue " in java? 如何在Clojure中解析日期字符串 - How to parse date string in Clojure 如何将不明确的字符串解析为日期? - How to parse ambiguous String into Date? 如何在 Java 中将字符串解析为日期 - How to parse String to Date in Java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM