Home > Java > javaTutorial > Why Does DateFormat Throw a \'Cannot Format Given Object as a Date\' Exception?

Why Does DateFormat Throw a \'Cannot Format Given Object as a Date\' Exception?

Linda Hamilton
Release: 2024-11-03 07:14:03
Original
385 people have browsed it

Why Does DateFormat Throw a

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

In this code:

  • inputFormat is used to parse the input string into a Date object.
  • outputFormat is then used to format the Date object in the desired "mm/yyyy" format.
  • The code handles potential ParseException exceptions when parsing the input string.

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template