How to convert a date to dd.MM.yyyy format in Java?

Farhan Shirgill Ansari picture Farhan Shirgill Ansari · May 31, 2015 · Viewed 26.7k times · Source

How can I convert the date(Mon Jan 12 00:00:00 IST 2015) in the format MM.dd.yyyy or dd.MM.yyyy?

I tried using the below approach

    String dateStr = "Mon Jan 12 00:00:00 IST 2015";

    DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
    System.out.println(formatter.format(dateStr));

but got,

Exception in thread "main" java.lang.IllegalArgumentException: 
Cannot format given Object as a Date

Answer

singhakash picture singhakash · May 31, 2015

You have to parse the string to Date then format that Date

String dateStr = "Mon Jan 12 00:00:00 IST 2015";

DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
DateFormat formatter1 = new SimpleDateFormat("dd.MM.yyyy");
System.out.println(formatter1.format(formatter.parse(dateStr)));

Demo