amateur amateur - 1 year ago 60
Java Question

convert from string "yyyyMMdd" to Calendar in java

I need to use Calendar class. This is my code, but it has an error certainly. How can I fix it?

String stringdate = "20161129";
String pattern = "yyyyMMdd";
Date date = new SimpleDateFormat(pattern).parse(stringdate);
Calendar cal = Calendar.getInstance();

Answer Source

Your code looks good...

2 things can happen her:

  1. you are not using the correct DAte class (import java.util.Date;)
  2. you are not considering (catching or rethrowing ) the ParseException

in both cases you will get a compilation error...

like type mismatch

enter image description here

or unhandled exception

enter image description here