Search code examples
javastringdatesimpledateformat

Java String to Date object of the format "yyyy-mm-dd HH:mm:ss"


I need to convert a String containing date into an date object. The String will be of the format "yyyy-mm-dd HH:mm:ss.SSSSSS" and I want the same format in an date object.

For instance I have a string "2012-07-10 14:58:00.000000", and I need the resultant date object to be of the same format.

I have tried the below methods but, the resultant is not as expected.

java.util.Date temp = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss.SSSSSS").parse("2012-07-10 14:58:00.000000");

DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
                Date thisDate = dateFormat.parse("2012-07-10 14:58:00.000000");

The result is "Tue Jan 10 14:58:00 EST 2012". Please let me know where I am going wrong.

Thanks, Yeshwanth Kota


Solution

  • java.util.Date temp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS").parse("2012-07-10 14:58:00.000000");
    

    The mm is minutes you want MM

    CODE

    public class Test {
    
        public static void main(String[] args) throws ParseException {
            java.util.Date temp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS")
                    .parse("2012-07-10 14:58:00.000000");
            System.out.println(temp);
        }
    }
    

    Prints:

    Tue Jul 10 14:58:00 EDT 2012