Java - 无法解析的日期异常

Java - Unparseable date exception

我有一个日期对象,其日期格式为:2015-09-21 10:42:48:000 我希望它以这种格式显示在 UI 上。21-Sep-2015 10:42:48

我使用的代码不工作并抛出这个:

Unparseable date exception: Unparseable date: "2015-09-21 10:42:48"

这是实际代码:

 String createdOn=f.getCreatedOn().toString();//f.getCreatedOn() returns a date object
 SimpleDateFormat format=new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
 Date date=format.parse(createdOn.substring(0,createdOn.length()-3));
 log.debug(">>>>>>date now is: "+date);
 model.addAttribute("date", date);
 model.addAttribute("info", messages);
 SimpleDateFormat format1=new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
 format1.format(date);
 log.debug(">>>>>>date now is again: "+date);

Unparseable date exception: Unparseable date: "2015-09-21 10:42:48"

因为您输入的日期格式是yyyy-MM-dd HH:mm:ss。但是您正在尝试使用 dd-MMM-yyyy HH:mm:ss 格式进行解析。

SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//change input date format here
Date date=format.parse("2015-09-21 10:42:48:000");
//Date date=format.parse(createdOn);//Here no need of subtracting 000 from your date
SimpleDateFormat format1=new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
System.out.println(format1.format(date));

SimpleDateFormat doc

您输入的日期格式不同。

String createdOn="2015-09-21 10:42:48:000";
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date=format.parse(createdOn.substring(0,createdOn.length()-4));
        System.out.println(">>>>>>date now is: "+date);

        SimpleDateFormat format1=new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
        format1.format(date);
        System.out.println(">>>>>>date now is again: "+date);

您使用错误的格式来显示和解析。

// We will use this for parsing a string that represents a date with the format declared below. If you try to parse a date string with a different format, you will get an exception like you did   
SimpleDateFormat parseFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

// This is for the way we want it to be displayed
SimpleDateFormat displayFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");

// Parse the date string
Date date = parseFormat.parse("2015-09-21 10:42:48:000");

// Format the date with the display format
String displayDate = displayFormat.format(date);

System.out.println(">>>>>>date now is: " + displayDate);