2013-01-13 59 views
1

我得到了String像這樣:2013-04-19,我想將其更改爲:April 19th 2013。我知道Java中有一些類,如SimpleDateFormat,但我不知道我應該使用什麼樣的函數。也許我需要選擇類Pattern?我需要一些幫助。將字符串日期更改爲另一個字符串日期

+2

你可以從這裏開始閱讀關於它:http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html – home

+5

快速查看任何SimpleDateFormat的例子將需要「解析」,然後將字符串「格式化」爲日期並返回字符串 –

+1

此外,您必須編寫自定義方式來說'19th',因爲它在SimpleDateFormat中不是標準的'。 –

回答

2

嘗試以下,這應該給你正確的 「日」, 「ST」, 「RD」和「nd」幾天。

public static String getDayOfMonthSuffix(final int n) { 
     if (n >= 11 && n <= 13) { 
      return "th"; 
     } 
     switch (n % 10) { 
      case 1: return "st"; 
      case 2: return "nd"; 
      case 3: return "rd"; 
      default: return "th"; 
     } 
    } 

public static void main(String[] args) throws ParseException { 
     Date d = new SimpleDateFormat("yyyy-MM-dd").parse("2013-04-19"); 

     int day = Integer.parseInt(new java.text.SimpleDateFormat("dd").format(d)); 
     SimpleDateFormat sdf = new SimpleDateFormat("MMMMM dd'" + getDayOfMonthSuffix(day) + "' yyyy"); 
     String s = sdf.format(d); 

     System.out.println(s); 
    } 

這將只是利用的SimpleDateFormat 類解析方法試試這個打印April 19th 2013

(改編自this post日終止)

+0

謝謝,我會盡快嘗試。 – Tsunaze

+0

它還會顯示「13rd」和「12nd」 –

1

試試這個:

String originalDate = "2013-04-19"; 
Date date = null; 
try { 
    date = new SimpleDateFormat("yyyy-MM-dd").parse(originalDate); 
} catch (Exception e) { 
} 
String formattedDate = new SimpleDateFormat("MMMM dd yyyy").format(date); 

將不打印ST,第二,第三等

1

new SimpleDateFormat("MMM dd YYYY").parse("2013-04-19"); 
相關問題