Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 631
Aaron Avatar asked Sep 04 '08 13:09

Aaron


People also ask

How do I convert a string to a calendar instance?

You can use following code to convert string date to calender format. String stringDate="23-Aug-10"; SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); Date date = formatter. parse(stringDate); Calendar calender = Calendar. getInstance(); calender.

Can we convert string to Date?

Let's see how to actually convert a String to a local date and time data type: Parse the API call: If the String value that we need to convert to the Date-time type is of ISO-801 format then we can simply call DateFormat and SimpleDateFormat classes using parse() methods.


1 Answers

In brief:

DateFormat formatter = new SimpleDateFormat("MM/dd/yy"); try {   Date date = formatter.parse("01/29/02"); } catch (ParseException e) {   e.printStackTrace(); } 

See SimpleDateFormat javadoc for more.

And to turn it into a Calendar, do:

Calendar calendar = Calendar.getInstance(); calendar.setTime(date); 
like image 88
Matt Sheppard Avatar answered Oct 03 '22 11:10

Matt Sheppard