簡體   English   中英

Java不可解析的日期異常

[英]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 ,這可能嗎?

SimpleDateFormat

 Letter Date or Time Component <br /> y Year <br /> 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

您需要解析StringDate格式正確輸入第一個String

yyyy-MM-dd HH:mm:ss

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

yyyy/MM/dd hh:mm:ss

並且不要期望Date類的toString()方法返回格式化值,它是固定實現

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM