Aaron Ferguson Aaron Ferguson - 4 months ago 7
Java Question

How to convert a date String to a Date or Calendar object?

I have a

String
representation of a date that I need to create a
Date
or
Calendar
object from. I've looked through
Date
and
Calendar
APIs but haven't found anything that can do this other than creating my own ugly parse method. I know there must be a way, does anyone know of a solution?

Answer

In brief:

DateFormat formatter = new SimpleDateFormat("MM/dd/yy");
Date date = formatter.parse("01/29/02");

See SimpleDateFormat javadoc for more.

And to turn it into a Calendar, do:

Calendar calendar = Calendar.getInstance();
calendar.setTime(date);