Java - 无法解析的日期异常

时间:2015-09-22 03:49:56

标签: java simpledateformat

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

我正在使用的代码不起作用并将其抛出:

  

无法解释的日期例外:无法解析的日期:“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);

3 个答案:

答案 0 :(得分:1)

  

无法解释的日期例外:无法解析的日期:" 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

答案 1 :(得分:0)

您的输入日期格式不同。

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);

答案 2 :(得分:0)

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

// 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);
相关问题