![](/img/trans.png)
[英]SimpleDateFormat ParseException: Unparseable date Error
[英]SimpleDateFormat with a pattern results in error Unparseable Date
我正在嘗試做一些非常簡單的事情-以當前的日期和時間,並以所需的格式解析它。
private final String datePattern = "yyyy:DDD";
private final String timePattern = "hh:mm:ss";
public void setDateAndTime(){
// Default constructor initializes to current date/time
Date currentDateAndTime = new Date();
SimpleDateFormat dateFormatter = new SimpleDateFormat(datePattern);
SimpleDateFormat timeFormatter = new SimpleDateFormat(timePattern);
try {
this.date = dateFormatter.parse(currentDateAndTime.toString());
this.time = timeFormatter.parse(currentDateAndTime.toString());
} catch (ParseException e){
System.out.println("Internal error - unable to parse date/time");
System.exit(1);
}
}
這導致異常:
無法解析的日期:“美國東部時間2010年11月6日星期六11:04:22”
這是一個完全有效的日期字符串,而我用來初始化SimpleDateFormat的模式似乎是正確的。
如何避免該錯誤,以及如何如上所述初始化SimpleDateFormat
?
String
獲取Date
Date
獲取String
您需要后者-因此請使用formatter.format(currentDateAndTime)
之所以會出現異常,是因為您通過toString()
將Date
轉換為String
,隨后又嘗試對其進行解析,但它不遵循您指定的格式。
你的代碼應該是
SimpleDateFormat dateFormatter = new SimpleDateFormat(datePattern); SimpleDateFormat timeFormatter = new SimpleDateFormat(timePattern); System.out.println(dateFormatter.format(currentDateAndTime));
簡而言之,除非輸出為字符串,否則無法格式化日期對象
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.