Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String (dd-MM-yyyy HH:mm) to Date (yyyy-MM-dd HH:mm) | Java

Tags:

java

I have a string in "dd-MM-yyyy HH:mm" and need to convert it to a date object in the format "yyyy-MM-dd HH:mm".

Below is the code I'm using to convert

oldScheduledDate = "16-05-2011 02:00:00";
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date oldDate = (Date)formatter.parse(oldScheduledDate);

Now when I print oldDate, i get

Sat Nov 01 02:00:00 GMT 21, which is completely wrong, what am I doing wrong here?

like image 392
Vivek Avatar asked Dec 22 '10 17:12

Vivek


People also ask

How to convert String to date yyyy-mm-dd in Java?

String start_dt = '2011-01-01'; DateFormat formatter = new SimpleDateFormat("YYYY-MM-DD"); Date date = (Date)formatter. parse(start_dt);

Can we convert String to date in Java?

By default, Java dates are in the ISO-8601 format, so if we have any string which represents a date and time in this format, then we can use the parse() API of these classes directly.


1 Answers

    String dateSample = "10-01-2010 21:10:05";

    String oldFormat = "dd-MM-yyyy HH:mm:ss";
    String newFormat = "yyyy-MM-dd HH:mm:ss";

    SimpleDateFormat sdf1 = new SimpleDateFormat(oldFormat);
    SimpleDateFormat sdf2 = new SimpleDateFormat(newFormat);


    try {
        System.out.println(sdf2.format(sdf1.parse(dateSample)));

    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
like image 174
jrey Avatar answered Oct 21 '22 13:10

jrey