Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.IllegalArgumentException: Cannot format given Object as a Date

Tags:

java

I recive a date in this format

2014-12-09 02:18:38

which i need to convert it to

09-12-2014 02:18:38

I tried converting this way

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 exception during Runtime

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)

Could anybody please help me how to resolve this .

like image 256
Pawan Avatar asked Dec 20 '22 08:12

Pawan


2 Answers

Try this

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 that m is for minutes, while M is for months.

like image 110
Predrag Maric Avatar answered Dec 28 '22 23:12

Predrag Maric


Instead of

String strDate = sdf.format(input);

use

String strDate = sdf.parse(input);

Also see this question

like image 28
Liam de Haas Avatar answered Dec 28 '22 23:12

Liam de Haas