2013-06-05 58 views
1

我正在開發一個Spring項目,我必須按上傳日期搜索文檔。所以當我把我的日期作爲DAO層中的一個方法的參數傳遞時,它的收到像是:Thu Jun 06 00:03:49 WEST 2013。我想格式化到:2013-06-06如何格式化java日期

我已經使用這個代碼,要做到這一點,但它返回06/06/13和日期格式的其他常量(如DateFormat.MEDIUM,...),不回我所期待的。

DateFormat shortDf = DateFormat.getDateInstance(DateFormat.SHORT);  
System.out.println(shortDf.format(new Date())); // return 06/06/13 it's short 

我也試着像那樣的SimpleDateFormat:

public static Date parseDate(String date, String format)throws ParseException { 
SimpleDateFormat formatter = new SimpleDateFormat(format,Locale.ENGLISH); 
return formatter.parse(date); 
} 

但它仍然拋出一個分析異常:

java.text.ParseException: Unparseable date: "Thu Jun 06 00:23:33 WEST 2013" 
at java.text.DateFormat.parse(DateFormat.java:337) 
at TestApp.main(TestApp.java:20) 

回答

1

如果要格式化一個日期到你自己的格式,如2013-06-06,SimpleDateFormatter是一個常用的解決方案。但是你的代碼出了什麼問題,你的格式化日期的返回類型是錯誤的。例如:

Date d=new Date(); 
String formattedDate=format(d); 

System.out.println("This is your date: "+formattedDate); 

public String format(String date){ 
    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); 
    return sdf.format(date); 
} 

要將日期格式化爲您自己的格式,請使用sdf.format,而不是sdf.parse。
sdf.parse用於將字符串轉換爲日期,而sdf.format用於將日期轉換爲指定格式的字符串。

sdf.parse返回Date,sdf.format返回String。

+0

是的,我已經找到這個解決方案,就像你所描述的 –

+1

pPlease如果你覺得它回答你的問題,請將此線程標記爲已回答,以便人們知道在此線程中找到了一個解決方案:) –

1

這是接近我可以得到:

DateFormat formatter = new SimpleDateFormat("EEE MMM dd hh:mm:ss z yyyy"); 
+0

+1這'DateFormat'將轉換所提出的'String'在'Date',只是確保通過正確的語言環境來識別日期和月份。 – eternay

0

你想要的格式是 - 2013年6月6日

使用

DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); 
try { 
     Date date = formatter.parse(new Date().toString()); 
} catch (ParseException ex) { 
     ex.printStackTrace(); 
} 
2

這應該工作你的情況:

DateFormat sourceFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US); 
    DateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd"); 

    try { 
     Date date = sourceFormat.parse("Thu Jun 06 00:23:33 WEST 2013"); 
     String formatted = targetFormat.format(date); 
     System.out.println(formatted); 
    } catch (ParseException e) { 
     e.printStackTrace(); 
    } 

首先,你需要解析日期使用正確的格式和區域設置(更改Locale.US以適合您)。您得到的異常是由不正確的解析格式或缺少語言環境引起的。

EEE MMM dd HH:mm:ss zzz yyyy 
Thu Jun 06 00:23:33 WEST 2013 

,然後使用這個格式化字符串格式化結果:

yyyy-MM-dd 
2013-06-06 

documentation

+0

你是對的,我必須使用格式化方法不是一個 DateFormat formatter = new SimpleDateFormat(「yyyy-MM-dd」); System.out.println(「Formated date:」+ formatter.format(currentDate)); // return 2013/06/06 like waited 非常感謝 –