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 a String
argument, also when the parameter type is declared to be Object
.
- Because of the exception you didn’t get around to discovering: there is also a bug in your format pattern string,
mm/yyyy
. Lowercase mm
os for minute of the hour. You need uppercase MM
for month.
- Finally the Java naming conventions say to use a lowercase first letter in variable names, so use lowercase
m
in monthYear
(also because java.time includes a MonthYear
class with uppercase M
, so to avoid confusion).
Links