2013-11-09 59 views
4

我有字符串11/08/2013 08:48:10Android的解析字符串的日期時間的SimpleDateFormat

我用SimpleDateFormat("MM/dd/yyyy HH:mm:ss")

,當IM解析它拋出一個異常:無法解析的日期

有什麼錯呢?

  String result = han.ExecuteUrl("http://"+han.IP+":8015/api/Values/GetLastChange"); 
      Log.d("Dal","result date time "+result); #result is 11/08/2013 08:48:10 
      SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); 

      Date convertedDate = new Date(); 
      try 
      { 

       convertedDate = dateFormat.parse(result); 
      } 
      catch (ParseException e) 
      { 
       e.printStackTrace(); 
      } 
+1

可以顯示代碼 –

+0

完成。漢變量只是爲了從url返回結果,它返回日期 – user2953680

回答

22

其工作嘗試解析您的日期這樣的..

String dtStart = "11/08/2013 08:48:10"; 
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); 
try { 
    date = format.parse(dtStart); 
    System.out.println("Date ->" + date); 
} catch (ParseException e) { 
    e.printStackTrace(); 
} 
+0

這是我在我的應用程序中使用的相同的代碼。 – user2953680

+0

你的答案和問題的區別在哪裏? –

4

工作代碼是在這裏。

您可以使用下面的代碼從字符串轉換爲Date

String myStrDate = "11/08/2013 08:48:10"; 
    SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); 
    try { 
     Date date = format.parse(myStrDate); 
     System.out.println(date); 
    } catch (ParseException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

對於反向,這意味着,從日期轉換爲字符串

SimpleDateFormat myFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); 
    try { 
     Date date = new Date(); 
     String datetime = myFormat.format(date); 
     System.out.println("Current Date Time in give format: " + datetime); 
    } catch (ParseException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

更多的參考,對於日期和時間格式。訪問developer site