2015-10-07 68 views
0

我想將字符串"10/7/2015 6:31am"轉換爲java中的Date。 我試過下面的代碼,但失敗了。在Java中使用Am/pm製造商轉換字符串

String value = "10/7/2015 6:31am"; 
SimpleDateFormat sdf = new SimpleDateFormat("M/d/yyyy h:mma"); 
return sdf.parse(value); 

SimpleDateFormat我應該使用什麼,請大家幫我

其實,我做了一個函數在Utils.java如下:

public static Date getDateValueByFormat(String value,String format) { 
     SimpleDateFormat sdf = new SimpleDateFormat(format); 
     try { 
      return sdf.parse(value); 
     } catch (ParseException e) { 
      e.printStackTrace(); 
      return null; 
     } 
    } 

調用此函數在其他類,如下所示:

String value = "10/7/2015 6:31am"; 
Date datetime = Utils.getDateValueByFormat(value, "M/d/yyyy h:mma"); 

不幸的是,拋出如下內容:

java.text.ParseException: Unparseable date: "10/7/2015 6:31am" 
    at java.text.DateFormat.parse(DateFormat.java:357) 
    at com.sapmle.common.util.Utils.getDateValueByFormat(Utils.java:28) 

有沒有想法?

PS:我用的jdk是1.7.0_79,有什麼問題嗎?

+4

它怎麼會失敗呢?它似乎爲我工作 – MadProgrammer

+0

它爲我工作 – Rehman

+0

爲我工作。 –

回答

0

Tom,prashant thakre, 非常感謝!

我successed通過自己的方式:

SimpleDateFormat sdf = new SimpleDateFormat(format,Locale.US);