DateFormat Cannot Format String Objects
In Java, the DateFormat class is designed specifically to format and parse Date objects, not strings. The provided code demonstrates a common error where a string representation of a date ("2012-11-17T00:00:00.000-05:00") is directly passed to the DateFormat.format() method. This results in the "Cannot format given Object as a Date" exception.
Two SimpleDateFormat Objects Approach
To resolve this issue, it's necessary to utilize two SimpleDateFormat objects: one for parsing the string into a Date object and another for formatting the Date object in the desired format. The following revised code addresses the issue:
<code class="java">import java.text.SimpleDateFormat; import java.text.ParseException; import java.util.Date; public class DateParser { public static void main(String args[]) { String MonthYear = null; String dateformat = "2012-11-17T00:00:00.000-05:00"; SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX", Locale.US); SimpleDateFormat outputFormat = new SimpleDateFormat("MM/yyyy", Locale.US); try { Date date = inputFormat.parse(dateformat); MonthYear = outputFormat.format(date); System.out.println(MonthYear); } catch (ParseException e) { System.err.println("Invalid date format."); } } }</code>
In this code:
The above is the detailed content of Why Does DateFormat Throw a \'Cannot Format Given Object as a Date\' Exception?. For more information, please follow other related articles on the PHP Chinese website!