Java Unparseable Date Exception

我试图用正斜杠替换连字符,但它导致一个unparseable date exception

  String test = "2014-04-01 05:00:00"; Date date = new SimpleDateFormat("YYYY/MM/dd hh:mm:ss", Locale.ENGLISH).parse(test); System.out.println(date); 

我有转换的必要值,有人能告诉我为什么它会返回错误吗? 另外,我想在格式的末尾附加一个am/pm marker ,这可能吗?

您需要首先以正确的格式将String解析为Date作为输入String

 yyyy-MM-dd HH:mm:ss 

然后你可以使用format()以其他格式打印它

 yyyy/MM/dd hh:mm:ss 

并且不要指望Date类的toString()方法返回格式化值,它是固定的实现

来自SimpleDateFormat

 Letter Date or Time Component 
y Year
Y Week year H Hour in day (0-23) h Hour in am/pm (1-12)

因此,使用yyyy一年和HH小时。 此外,您将字段分隔- ,而不是/

 Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH).parse(test); 

执行此操作后,正如@JigarJoshi所怀疑的那样,您可以将Date格式化为另一种格式:

 String dateInDesiredFormat = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss a", Locale.ENGLISH).format(date); 

或者写成完整的代码块:

 DateFormat parse = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.ENGLISH); DateFormat format = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss a", Locale.ENGLISH); String test = "2014-04-01 05:00:00"; Date date = parse.parse(test); System.out.println(format.format(date)); 

产生以下输出:

 2014/04/01 05:00:00 AM 
 String test = "2014-04-01 05:00:00"; SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); Date oldDate = formatter.parse(test); formatter.applyPattern("yyyy/MM/dd HH:mm:ss a"); Date newDate = formatter.parse(formatter.format(oldDate)); System.out.println(formatter.format(newDate));