Home >Java >javaTutorial >How to Resolve the \'Cannot format given Object as a Date\' Exception in Java?
Exception "Cannot format given Object as a Date" in Java: Resolved
When attempting to format a string representing a date into a specific format, developers may encounter the "Cannot format given Object as a Date" exception. This occurs because the provided DateFormat instance is used to format Date values, not strings.
To address this issue, utilize two SimpleDateFormat objects: one for parsing (converting string to Date) and one for formatting (converting Date to string). Here's an example:
<code class="java">import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class DateParser { public static void main(String[] args) throws Exception { // Define formats for input and output DateFormat outputFormat = new SimpleDateFormat("MM/yyyy", Locale.US); DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX", Locale.US); // Parse input string into a Date object String inputText = "2012-11-17T00:00:00.000-05:00"; Date date = inputFormat.parse(inputText); // Format the Date object using the desired format String outputText = outputFormat.format(date); System.out.println(outputText); // Output: 11/2012 } }</code>
Note that it's advisable to specify a locale when creating the SimpleDateFormat instances to ensure correct date and time handling based on the user's locale. Additionally, consider using the Joda Time library for advanced date and time manipulation capabilities.
The above is the detailed content of How to Resolve the \'Cannot format given Object as a Date\' Exception in Java?. For more information, please follow other related articles on the PHP Chinese website!