Home > Java > javaTutorial > body text

How to Resolve the \'Cannot format given Object as a Date\' Exception in Java?

DDD
Release: 2024-10-31 03:35:30
Original
793 people have browsed it

How to Resolve the

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!