Java : Cannot format given Object as a Date
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.
java.time
I should like to contribute the modern answer. The SimpleDateFormat
class is notoriously troublesome, and while it was reasonable to fight one’s way through with it when this question was asked six and a half years ago, today we have much better in java.time, the modern Java date and time API. SimpleDateFormat
and its friend Date
are now considered long outdated, so don’t use them anymore.
DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("MM/uuuu");
String dateformat = "2012-11-17T00:00:00.000-05:00";
OffsetDateTime dateTime = OffsetDateTime.parse(dateformat);
String monthYear = dateTime.format(monthFormatter);
System.out.println(monthYear);
Output:
11/2012
I am exploiting the fact that your string is in ISO 8601 format, the international standard, and that the classes of java.time parse this format as their default, that is, without any explicit formatter. It’s stil true what the other answers say, you need to parse the original string first, then format the resulting date-time object into a new string. Usually this requires two formatters, only in this case we’re lucky and can do with just one formatter.
What went wrong in your code
- As others have said,
SimpleDateFormat.format
cannot accept aString
argument, also when the parameter type is declared to beObject
. - Because of the exception you didn’t get around to discovering: there is also a bug in your format pattern string,
mm/yyyy
. Lowercasemm
os for minute of the hour. You need uppercaseMM
for month. - Finally the Java naming conventions say to use a lowercase first letter in variable names, so use lowercase
m
inmonthYear
(also because java.time includes aMonthYear
class with uppercaseM
, so to avoid confusion).
Links
-
Oracle tutorial: Date Time explaining how to use
java.time
. - Wikipedia article: ISO 8601
You have one DateFormat
, but you need two: one for the input, and another for the output.
You've got one for the output, but I don't see anything that would match your input. When you give the input string to the output format, it's no surprise that you see that exception.
DateFormat inputDateFormat = new SimpleDateFormat("yyyy-MM-ddhh:mm:ss.SSS-Z");