Cannot convert my String to Date

冷暖自知 提交于 2019-12-08 05:53:52

问题


i was searching how to convert a string to a date, so i've found some examples on stacko. . So i used SimpleDateFormat and tried to parse but my compiler (Gradle from AndroidStudio) send me this error : Unhandled exception : java.text.ParseException. There is my code :

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
[...]

}

Why is there an error? Someone can explain that to me? I'm a beginner in java and i'm sorry for my bad english, and i hope someone can help me on this. Thanks


回答1:


The parse method throws a ParseException. You need to insert a catch block or your method should throw ParseException in order to get rid of the error:

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();
    } 
}

OR

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


来源:https://stackoverflow.com/questions/17399761/cannot-convert-my-string-to-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!