ayampenyet ayampenyet - 2 months ago 12
Java Question

How to convert date to string and to date again?

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

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
    }
Comments