使用Am / pm maker将字符串转换为Java中的日期

时间:2015-10-07 05:53:12

标签: java date format

我想在java中将字符串"10/7/2015 6:31am"转换为Date。 我试过跟随代码,但失败了。

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,有什么问题吗?

1 个答案:

答案 0 :(得分:0)

汤姆,prashant thakre, 非常感谢你!

我按你的方式成功:

SimpleDateFormat sdf = new SimpleDateFormat(format,Locale.US);
相关问题