2013-12-19 31 views
-1

我有一個關於如何將日期顯示爲歐式風格的問題,如2013年4月4日至2013年4月4日。我該如何解決這個問題?任何幫助將不勝感激。當我運行我的程序,我得到這樣的:更改日期爲歐洲風格的java

run: 
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 47 
at java.lang.String.substring(String.java:1907) 
at Testing1.convertDate(Testing1.java:7) 
at Testing1.main(Testing1.java:14) 
Java Result: 1 
BUILD SUCCESSFUL (total time: 0 seconds) 

下面是我的代碼:

Testing1.java:

public class Testing1{ 

public static String convertDate(String amerDate){ 
    String month = amerDate.substring(0, '/'); 
    String date = amerDate.substring('/', '/'); 
    int year = amerDate.indexOf("\4d"); 
    return date + " - " + month + " - " + year; 
} 
public static void main(String args[]){ 
    String date = "4/4/2013"; 
    date = convertDate(date); 
    System.out.println(date); 
} 
} 
+0

'date = date.replace('/',' - ')'?如果你正在得到一個Date對象,那麼使用'DateFormat'就可以了。 –

+0

考慮使用像SimpleDateFormat這樣的內置東西來代替:令人討厭的陳詞濫調:不要重新發明輪子。 – Bathsheba

回答

1

使用SimpleDataFormat。要獲得像4-4-2013這樣的日期,請執行以下操作:

SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); 
String formattedDate = formatter.format(yourDate); 

查閱文檔以獲取更多信息。

相關問題