无法将我的String转换为Date

ben*_*ous 1 java string date date-format simpledateformat

我正在搜索如何将字符串转换为日期,所以我在stacko上找到了一些例子..所以我使用SimpleDateFormat并尝试解析但我的编译器(来自AndroidStudio的Gradle)发送给我错误:未处理的异常:java.text.ParseException.有我的代码:

public static int compareDate(String sdate1, String sdate2) {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd", Locale.FRANCE);
    Date date1 = simpleDateFormat.parse(sdate1); // there is the error
[...]

}
Run Code Online (Sandbox Code Playgroud)

为什么会出错?有人可以向我解释一下吗?我是java的初学者,我很抱歉我的英语不好,我希望有人可以帮助我.谢谢

Rah*_*ate 7

parse方法抛出一个ParseException.你需要插入一个catch块或你的方法应该抛出ParseException,以摆脱错误:

public static int compareDate(String sdate1, String sdate2) {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd", Locale.FRANCE);
    try {
        Date date1 = simpleDateFormat.parse(sdate1);
    } catch (ParseException e) {              // Insert this block.
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 
}
Run Code Online (Sandbox Code Playgroud)

要么

public static int compareDate(String sdate1, String sdate2) throws ParseException{
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd", Locale.FRANCE);
    Date date1 = simpleDateFormat.parse(sdate1); 
}
Run Code Online (Sandbox Code Playgroud)