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?
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With