Java.lang.IllegalArgumentException: Cannot format the given object as a date

I am getting date in this format

2014-12-09 02:18:38

      

which I need to convert to

09-12-2014 02:18:38

      

I tried to convert this path

import java.text.ParseException;
import java.text.SimpleDateFormat;
public class TestDate {
    public static void main(String[] args) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("dd-mm-YYYY HH:mm:ss");
        String input = "2014-12-09 02:18:38";
        String strDate = sdf.format(input);
        System.out.println(strDate);
    }
}

      

But I am getting this runtime exception

Exception in thread "main" java.lang.IllegalArgumentException: Cannot format given Object as a Date
    at java.text.DateFormat.format(DateFormat.java:301)
    at java.text.Format.format(Format.java:157)
    at TestDate.main(TestDate.java:15)

      

Can someone please help me how to solve this.

+3


source to share


4 answers


try it

public static void main(String[] args) throws ParseException {
    SimpleDateFormat sdfIn = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    SimpleDateFormat sdfOut = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
    String input = "2014-12-09 02:18:38";
    Date date = sdfIn.parse(input);

    System.out.println(sdfOut.format(date));
}

      



Also note what m

is in minutes and m

is over several months.

+4


source


Instead

String strDate = sdf.format(input);

      

using



String strDate = sdf.parse(input);

      

Also see this question

+3


source


    SimpleDateFormat sdf = new SimpleDateFormat("dd-mm-YYYY HH:mm:ss");

    // String to Date:
    String input = "2014-12-09 02:18:38";
    Date date = sdf.parse(input);

    // Date to String:
    String strDate = sdf.format(date);
    System.out.println(strDate);

      

0


source


SimpleDateFormat in can be used to format a Date object.

First you need to parse your string into the Data object using the format of the declared SimpleDateFormat. After that, you can output it using the second SimpleDataFromat to the desired line.

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String input = "2014-12-09 02:18:38";
    Date dt = sdf.parse(input);

    SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");        
    String strDate = sdf2.format(dt);
    System.out.println(strDate);

      

0


source







All Articles