Home >Java >javaTutorial >How to Handle \'Cannot Format Given Object as a Date\' Error in Java?

How to Handle \'Cannot Format Given Object as a Date\' Error in Java?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-31 12:53:30694browse

How to Handle

Handling "Cannot Format Given Object as a Date" Error in Java

When attempting to convert a given date into a specific format, Java developers may encounter the exception: "java.lang.IllegalArgumentException: Cannot format given Object as a Date." This error occurs when trying to format an unsupported object as a date.

To resolve this issue, we need to use the correct formatting strategy. The DateFormat.format method accepts Date objects as input. In the provided example, the input value is a string representing a date, not a Date object.

The solution is to use two separate SimpleDateFormat objects: one for parsing the input string and another for formatting the result. For instance:

<code class="java">// Define the output format (mm/yyyy for months and years)
DateFormat outputFormat = new SimpleDateFormat("mm/yyyy", Locale.US);

// Define the input format (yyyy-MM-dd'T'HH:mm:ss.SSSX)
DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX", Locale.US);

String inputText = "2012-11-17T00:00:00.000-05:00";

try {
    // Parse the input string as a Date object
    Date date = inputFormat.parse(inputText);

    // Format the Date object using the desired format
    String outputText = outputFormat.format(date);
} catch (ParseException e) {
    // Handle parsing exceptions here
}</code>

By following this approach, we can effectively convert a string representing a date into a desired format while avoiding the "Cannot format given Object as a Date" error.

The above is the detailed content of How to Handle \'Cannot Format Given Object as a Date\' Error in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn