Home >Java >javaTutorial >How to Convert a Date String \'2012-11-17T00:00:00.000-05:00\' to \'mm/yyyy\' Format in Java?
Question:
How can a date in the format "2012-11-17T00:00:00.000-05:00" be converted into "mm/yyyy" in Java?
Error Encountered:
When attempting to use DateFormat.format directly on the string representation of the date, an exception is thrown:
java.lang.IllegalArgumentException: Cannot format given Object as a Date
Solution:
The key is to recognize that DateFormat.format works specifically with Date values, not string representations of dates. Therefore, the following two-step approach should be used:
Parse the input string into a Date object:
<code class="java">DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX", Locale.US); Date date = inputFormat.parse(inputText);</code>
Format the Date object into the desired output format:
<code class="java">DateFormat outputFormat = new SimpleDateFormat("MM/yyyy", Locale.US); String outputText = outputFormat.format(date);</code>
Example Usage:
<code class="java">String inputText = "2012-11-17T00:00:00.000-05:00"; String outputText = new SimpleDateFormat("MM/yyyy", Locale.US).format(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX", Locale.US).parse(inputText));</code>
By following these steps, the date string can be converted to the desired "mm/yyyy" format without encountering the Cannot format given Object as a Date exception.
The above is the detailed content of How to Convert a Date String \'2012-11-17T00:00:00.000-05:00\' to \'mm/yyyy\' Format in Java?. For more information, please follow other related articles on the PHP Chinese website!