2014-03-07 152 views
-1

我怎麼能轉換日期的形式Java的轉換日期從一種格式轉換爲另一種

2013年1月10日9時49分19秒

1月10日

這兩個值都是字符串類型。

+2

http://developer.android.com/reference/java/text/SimpleDateFormat.html – david99world

+2

我無法想象你如何能夠*不*發現如何解析和格式化與Java的日期。 –

回答

5

我添加的代碼制定出正確的後綴,因爲這不是標準的JDK的一部分。公平地說,這可能是這個問題的唯一不只是SimpleDateFormat#format()電話。

static String[] suffixes = 
      // 0  1  2  3  4  5  6  7  8  9 
      { "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th", 
      // 10 11 12 13 14 15 16 17 18 19 
       "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", 
      // 20 21 22 23 24 25 26 27 28 29 
       "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th", 
      // 30 31 
       "th", "st" }; 

public static void main(String args[]) throws ParseException { 
    String string = "2013-01-10 09:49:19"; 
    Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH).parse(string); 
    SimpleDateFormat dayFormat = new SimpleDateFormat("dd"); 
    SimpleDateFormat monthFormat = new SimpleDateFormat("MMM"); 
    String dayStr = 
      dayFormat.format(date) 
        + suffixes[Integer.parseInt(dayFormat.format(date))] 
        + " " + monthFormat.format(date) + "."; 
    System.out.println(dayStr); 
} 
+0

+1 forawesome答案。 –

1
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2013-01-10 09:49:19"); 
String format = new SimpleDateFormat("dd'th' MMM").format(date); 
System.out.println(format); 

輸出是:

10th Jan 
+0

這是不正確的,好像它是在本月3日,它會說1月3日,這是不正確的。 – david99world

0

使用DateFormat類

DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.ENGLISH);

System.out.println(df.parse(myDateInString));

我想你應該在周圍嘗試捕捉可能的異常的語句。

相關問題