将String转换为日期,抛出ParseException

时间:2013-07-11 09:08:38

标签: java android datetime

我想将字符串11-7-2013 10:51:10转换为Date object

formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss"); 
try {
    String date = "11-7-2013 10:51:10"
    return formatter.parse(date);
} catch (ParseException e) {
    e.printStackTrace();
}

我有以下代码,但我得到了ParseException

6 个答案:

答案 0 :(得分:2)

尝试

formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); 

答案 1 :(得分:2)

使用

formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); 
try {
    String date = "11-7-2013 10:51:10"
    return formatter.parse(date);
} catch (ParseException e) {
    e.printStackTrace();
}

在SimpleDateFormat中,传递给构造函数的字符串与日期格式相同,表示日期格式由此格式化程序解析。

答案 2 :(得分:1)

您需要在日期格式中使用“ - ”代替“/”,因为日期字符串包含“ - ”,

formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); 
try {
    String date = "11-7-2013 10:51:10"
    return formatter.parse(date);
} catch (ParseException e) {
    e.printStackTrace();
}

答案 3 :(得分:1)

formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); 

的实例
formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss"); 

答案 4 :(得分:1)

这里有两种方法

"dd/MM/yyyy hh:mm:ss" with String Date ="11/7/2013 10:51:10";

 "dd-MM-yyyy hh:mm:ss" with String Date="11-7-2013 10:51:10";

答案 5 :(得分:-1)

请参阅以下格式

tring string =“2010年1月2日”; Date date = new SimpleDateFormat(“MMMM d,yyyy”,Locale.ENGLISH).parse(string);