How to convert date to string and to date again?

ayampenyet picture ayampenyet · Oct 21, 2013 · Viewed 130.6k times · Source

Hi i want to convert the current date to this format YYYY-MM-DD. However, it will convert the date into String format, but i want to convert it back into Date format. So can anyone advise on this?

This is my code so far

 DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
 Date date = new Date();
 String datestring = dateFormat.format(date); 

Answer

Kanchan picture Kanchan · Oct 21, 2013

try this:

 String DATE_FORMAT_NOW = "yyyy-MM-dd";
 Date date = new Date();
 SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
 String stringDate = sdf.format(date );
    try {
        Date date2 = sdf.parse(stringDate);
    } catch(ParseException e){
     //Exception handling
    } catch(Exception e){
     //handle exception
    }