[英]Java - Unparseable date exception
我有一个日期对象,其日期格式为: 2015-09-21 10:42:48:000
我希望它以这种格式显示在UI上。 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);
无法解析的日期例外:无法解析的日期:“ 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));
您输入的日期格式不同。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.