Sparrow Sparrow - 4 months ago 9
Java Question

How to convert a String to Date of format yyyy-MM-dd HH:MM:ss

I have a String like

"2015-07-16 17:07:21"
. I want to convert it into a Date of same format. I tried something like this.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:MM:ss");
Date date = sdf.parse("2015-07-16 17:07:21");


But output was different format like Thu
Jul 16 17:00:21 IST 2015
. How can i get it work as i need. can anyone help me. I know this might be a duplicate but i didn't find any luck.

Answer

From the Java API https://docs.oracle.com/javase/8/docs/api/java/util/Date.html

The class Date represents a specific instant in time, with millisecond precision.

Try to understand the difference/connection of Date and DateFormat.

public static void main(String [] args) throws ParseException{
    String dateString = "2015-07-16 17:07:21";
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    // use SimpleDateFormat to define how to PARSE the INPUT
    Date date = sdf.parse(dateString);

    // at this point you have a Date-Object with the value of
    // 1437059241000 milliseconds
    // It doesn't have a format in the way you think

    // use SimpleDateFormat to define how to FORMAT the OUTPUT
    System.out.println( sdf.format(date) );

    sdf = new SimpleDateFormat();
    System.out.println( sdf.format(date) );

  // ....
}

Output: (Please note that the Date stays the same, just its representation (format) changes)

2015-07-16 17:07:21
7/16/15 5:07 PM