java 为什么我会收到无法解析的日期异常?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31519190/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 18:44:36  来源:igfitidea点击:

Why am I getting an unparseable date exception?

javadatesimpledateformat

提问by Jonathan Caicedo

I am not able to parse a date using SimpleDateFormat. I have tried this code:

我无法使用SimpleDateFormat. 我试过这个代码:

SimpleDateFormat fechas = new SimpleDateFormat("dd/MM/yyyy hh:mm");

if (data[i].length() > 1) {
    Date f = (Date) fechas.parse(data[i]);
    System.out.println(i + " " + f);
}

I get the following error:

我收到以下错误:

Exception in thread "main" java.text.ParseException: Unparseable date: "01/06/2015 8:20

"

I have the same problem again with the following code:

使用以下代码我再次遇到同样的问题:

SimpleDateFormat fech = new SimpleDateFormat(" yyyy/MM/dd HH:mm:ss");
Date date = (Date) fech.parse(data[i]);
System.out.println(date);

Which gives the error

这给出了错误

Exception in thread "main" java.text.ParseException: Unparseable date: "00015/06/01  08:20:15"

How can I fix this problem?

我该如何解决这个问题?

回答by durron597

When using SimpleDateFormat, the date format has to match exactly. In your example, you include the date, but in your date format, you also specify the hours and minutes. If your data had that text, it would work. For instance, using your first example:

使用时SimpleDateFormat,日期格式必须完全匹配。在您的示例中,您包括日期,但在您的日期格式中,您还指定了小时和分钟。如果您的数据具有该文本,它将起作用。例如,使用您的第一个示例:

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class DateDemo {
  public static void main(String args[]) throws Exception {
    String yourData = "01/06/2015";
    String matchingData = "01/06/2015 13:00";
    SimpleDateFormat fechas = new SimpleDateFormat("dd/MM/yyyy hh:mm");

    Date matchingDate = fechas.parse(matchingData);
    System.out.println("String: \"" + matchingData + "\" parses to " + matchingDate);
    Date yourDate = fechas.parse(yourData);
    System.out.println("String: \"" + yourData + "\" parses to " + yourDate);
  }
}

This outputs:

这输出:

String: "01/06/2015 13:00" parses to Mon Jun 01 13:00:00 CDT 2015
Exception in thread "main" java.text.ParseException: Unparseable date: "01/06/2015"
        at java.text.DateFormat.parse(DateFormat.java:366)
        at Demo.main(Demo.java:14)

回答by Basil Bourque

tl;dr

tl;博士

How can I fix this problem?

我该如何解决这个问题?

Match your formatting pattern to your input.

将您的格式模式与您的输入相匹配。

LocalDateTime.parse( 
    "01/06/2015 8:20" , 
    DateTimeFormatter.ofPattern( "dd/MM/uuuu H:m" )
)
.toString()

2015-06-01T08:20

2015-06-01T08:20

java.time

时间

As others stated, your formatting pattern failed to match your string input.

正如其他人所说,您的格式模式无法匹配您的字符串输入。

Also, you are using troublesome old date-time classes supplanted years ago by the java.timeclasses.

此外,您正在使用多年前由java.time类取代的麻烦的旧日期时间类。

Your time-of-day hour lacks a padding zero. So you should have been using one hrather than two hh. Furthermore, a lowercase hmeans 12-hour clock, where your input seems to be 24-hour clock given the lack of an AM/PM indicator. So an uppercase His in order.

您的时间小时没有填充零。所以你应该使用 oneh而不是 two hh。此外,小写h表示 12 小时制,鉴于缺少 AM/PM 指示器,您的输入似乎是 24 小时制。所以大写H是有序的。

String input = "01/06/2015 8:20" ;  // Notice the lack of a padding zero on the hour.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu H:m" ) ;
LocalDateTime ldt = LocalDateTime.parse( input , f ) ;

ldt.toString(): 2015-06-01T08:20

ldt.toString(): 2015-06-01T08:20



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 类?

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 的试验场。你可能在这里找到一些有用的类,比如IntervalYearWeekYearQuarter,和更多

回答by Ankit Nigam

The pattern in your date Stringas well as in SimpleDateFormat()should match :-

您的日期String和日期中的模式SimpleDateFormat()应该匹配:-

SimpleDateFormat("dd/MM/yyyy hh:mm")will work with 01/06/2015 2:24

SimpleDateFormat("dd/MM/yyyy hh:mm")将与 01/06/2015 2:24

AND

SimpleDateFormat("yyyy/MM/dd HH:mm:ss")will work with 2015/06/01 08:20:15

SimpleDateFormat("yyyy/MM/dd HH:mm:ss")将与 2015/06/01 08:20:15

For complete list, see Offical Oracle Doc here

有关完整列表,请参阅此处的官方 Oracle 文档

回答by Stelan Briyan Simonsz

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Test {
    public static void main(String[] args) {
        String dateText = "18/07/2015 05:30";        
        DateFormat fechas = new SimpleDateFormat("dd/MM/yyyy hh:mm");
        try {
            Date parse = fechas.parse(dateText);
            System.out.println("Date : " + fechas.format(parse));
        } catch (ParseException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        }
    }    
}

I do this like that source code

我这样做就像那个源代码