Home  >  Article  >  Java  >  How to Handle \"Cannot Format Object as Date\" Exception in Java?

How to Handle \"Cannot Format Object as Date\" Exception in Java?

Susan Sarandon
Susan SarandonOriginal
2024-10-30 19:46:30814browse

How to Handle

Cannot Format Object as Date in Java

In Java, when trying to format a given object as a date using the DateFormat.format method, you may encounter the following exception:

java.lang.IllegalArgumentException: Cannot format given Object as a Date

This error occurs when the object you attempt to format is not a Date instance. In your case, you are attempting to format a string ("2012-11-17T00:00:00.000-05:00") as a date using a SimpleDateFormat instance configured with the "mm/yyyy" pattern.

Solution

To address this issue, you should use two SimpleDateFormat objects: one for parsing the input string into a Date instance and another for formatting the resulting Date into the desired format:

<code class="java">import java.text.SimpleDateFormat;
import java.util.Date;

public class DateParser {

    public static void main(String args[]) {
        String monthYear = null;

        // Create input format to parse from "yyy-MM-dd'T'HH:mm:ss.SSSX"
        SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");

        // Create output format to format to "MM/yyyy"
        SimpleDateFormat outputFormat = new SimpleDateFormat("MM/yyyy");

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

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

            // Format the parsed Date into the desired format
            monthYear = outputFormat.format(date);

            System.out.println(monthYear);
        } catch (ParseException e) {
            System.err.println("Input string is not a valid date: " + e.getMessage());
        }
    }
}</code>

This approach separates the parsing and formatting operations, ensuring that the input is properly converted to a Date instance before attempting to format it using the specified pattern.

The above is the detailed content of How to Handle \"Cannot Format Object as Date\" Exception 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