javadate

String to Date conversion giving wrong date


I have string date:

"01/15/2015 12:00 AM" 

and I want a date object in "dd/MM/yyyy' 'HH:mm:ss" format. How can I achieve this?

I have tried:

String datetime1 ="01/15/2015 12:00 AM"
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm a");
Date datepicker1 = dateFormat.parse(datetime1);

But this datepicker is having a date in 2016. I don't know why this is happening.


Solution

  • Change it to:

    DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm a");
                                                   ↑
    

    You flipped MM and dd..

    I guess that what happened here is that Java thought you have 15 months, added it to the day "1" in the year 2015, so you got 2016.. Your'e not far from implementing a time machine :)