1

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

6
  • Can you show us how does your string look like? Commented Jul 1, 2013 at 7:59
  • 1
    It's an issue with your locale Commented Jul 1, 2013 at 8:00
  • I enter in my function a String with the format "2013/07/01" Commented Jul 1, 2013 at 8:01
  • it still does not work. Even if I change local Commented Jul 1, 2013 at 8:03
  • try deleting locale argument Commented Jul 1, 2013 at 8:11

1 Answer 1

7

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); 
}
Sign up to request clarification or add additional context in comments.

5 Comments

That works :) . So it was just cause i don't used a try/catch bloc.
@bengous That works?? then accept it as answer, also give an upvote if it was hwlpful
And make sure you understand what you are doing: if a method CAN throw an Exception that does not extends RuntimeException, you HAVE TO handle it by catching it or declaring your method can throw that exception.
i cannot Upvote already :) . And @Pablo Lozano, i don't understand why i have to this on my code, so if you can explain me why i have to use a try/catch, i will be happy

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.