Java : Cannot format given Object as a Date

java

Solution

`DateFormat.format` only works on `Date` values.

You should use two SimpleDateFormat objects: one for parsing, and one for formatting. For example:

// Note, MM is months, not mm
DateFormat outputFormat = new SimpleDateFormat("MM/yyyy", Locale.US);
DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX", Locale.US);

String inputText = "2012-11-17T00:00:00.000-05:00";
Date date = inputFormat.parse(inputText);
String outputText = outputFormat.format(date);

EDIT: Note that you may well want to specify the time zone and/or locale in your formats, and you should also consider using Joda Time instead of all of this to start with - it's a much better date/time API.

Problem

I have Date in this format (2012-11-17T00:00:00.000-05:00). I need to convert the date into this format mm/yyyy. I tried this way, but I am getting this Exception. ``` Exception in thread "main" java.lang.IllegalArgumentException: Cannot format given Object as a Date at java.text.DateFormat.format(Unknown Source) at java.text.Format.format(Unknown Source) at DateParser.main(DateParser.java:14) ``` Please see my code below: ``` import java.text.SimpleDateFormat; import java.util.Date; public class DateParser { public static void main(String args[]) { String MonthYear = null; SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm/yyyy"); String dateformat = "2012-11-17T00:00:00.000-05:00"; MonthYear = simpleDateFormat.format(dateformat); System.out.println(MonthYear); } } ```

Original source