2015-10-07 71 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);