2

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
Farhan stands with Palestine
  • 13,890
  • 13
  • 58
  • 105

2 Answers2

6

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

singhakash
  • 7,891
  • 6
  • 31
  • 65
  • If the date is Mon Jan 32 00:00:00 IST 2015, it gets converted to date of next month(in this case, 01.02.2015), how can I prevent this. – Farhan stands with Palestine Jun 01 '15 at 12:34
  • use `setLenient(false)` to validate date check the [docs](http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html#setLenient(boolean)) for more info. – singhakash Jun 01 '15 at 16:30
3
String dateStr = "Mon Jan 12 00:00:00 IST 2015";

First you have to parse your string to a date:

DateFormat parser = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
Date date = parser.parse(dateStr);

and then you can format it:

DateFormat formatter = new SimpleDateFormat("dd.MM.yyyy");
System.out.println(formatter.format(date));
Jens
  • 67,715
  • 15
  • 98
  • 113