-1

如何使用 SimpleDateFormat 将字符串“06\24\1989”(如果用户这样输入)解析为日期格式(MM/DD/YYYY)。

4

2 回答 2

2

只需使用 aSimpleDateFormat将其解析String为 aDate并使用另一个将其转换回String您想要的格式的 a 。请记住在字符串文字中使用双反斜杠(\是转义字符)

SimpleDateFormat sdfParse = new SimpleDateFormat("MM\\dd\\yyyy");
SimpleDateFormat sdfFormat = new SimpleDateFormat("MM/dd/yyyy");
try{
    Date date = sdfParse.parse("09\\24\\1989");
    System.out.println(sdfFormat.format(date)); // Prints 09/24/1989
}
catch (ParseException e){
    System.out.println("Invalid date");
}

当然,您可以将所有反斜杠替换为正斜杠,new SimpleDateFormat("MM/dd/yyyy");如果您想验证它是有效日期,请尝试用 a 解析它。

String input = "09\\24\\1989".replace("\\", "/");
SimpleDateFormat sdfParse = new SimpleDateFormat("MM\\dd\\yyyy");    
try{
    sdfFormat.parse(input))
}
catch (ParseException e){
    System.out.println("Invalid date");
}
于 2013-03-21T11:31:20.050 回答
0

try {
    String dateString = "09\\24\\1989";
    SimpleDateFormat format = new SimpleDateFormat("MM\\DD\\YYYY");
    Date myDate = format.parse(dateString);
} catch (ParseException e) {
    //what you want
}
于 2013-03-21T11:38:23.623 回答