2012-02-15 175 views
2

我有一個日期進來。所以例如02/16/2012。我需要做的是使用我的數據庫格式將其轉換爲2012-02-16。我想這將是非常簡單的。但我無法工作。這是我的日期解析器。DateFormat解析錯誤

String endDateString = "02/16/2012" 
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd"); 
endDate = dateFormat.parse(endDateString) 

有什麼建議嗎?謝謝。

回答

1

你應該分析它從一個正確的格式,然後用另一個正確的格式轉換爲TO字符串。你在做什麼 - 試圖用yyyy-MM-dd格式來解釋MM/dd/yyyy格式的日期,即不正確。

樣品

public static void main(String[] args) throws ParseException { 

    SimpleDateFormat sourceFormat = new SimpleDateFormat("MM/dd/yyyy"); 
    SimpleDateFormat destinationFormat = new SimpleDateFormat("yyyy-MM-dd"); 

    String sourceDateString = "02/16/2012"; 
    String destinationDateString; 

    Date dat; // this object stores "perfect" date object 

    // interpreting string with input format and converting it to date 
    dat = sourceFormat.parse(sourceDateString); 

    // expressing date object as string in destination format 
    destinationDateString = destinationFormat.format(dat); 

    System.out.format("Done from %s to %s\n", sourceDateString, destinationDateString)); 


} 
-1

你用錯了格式解析

new SimpleDateFormat("MM/dd/yyyy"); 
0

您指定的日期格式必須與您輸入的日期格式如下所示:

SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy"); 
4

你想要做的是解析輸入格式爲Date對象

final SimpleDateFormat idf = new SimpleDateFormat("MM/dd/yyyy"); 
final Date indate = idf.parse("02/16/2012"); 

然後重新格式化Date對象的格式,你的願望

final SimpleDateFormat odf = new SimpleDateFormat("yyyy-MM-dd"); 
final String s = odf.format(indate); 
0

這段代碼可以告訴你如何完成它。

SimpleDateFormat inputDateFormat = new SimpleDateFormat("MM/dd/yyyy"); 
SimpleDateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd"); 
String endDateString = "02/16/2012"; 
String endDate =  outputDateFormat.format(inputDateFormat.parse(endDateString)); 

參考:SimpleDateFormat

0

您還可以在數據庫級別轉換的日期。例如MySQL有一個函數STR_TO_DATE。在你的情況下,這將是STR_TO_DATE('02/16/2012','%m /%d /%Y')