Home > Java > javaTutorial > How to Convert a Date String \'2012-11-17T00:00:00.000-05:00\' to \'mm/yyyy\' Format in Java?

How to Convert a Date String \'2012-11-17T00:00:00.000-05:00\' to \'mm/yyyy\' Format in Java?

Susan Sarandon
Release: 2024-11-02 15:57:29
Original
773 people have browsed it

How to Convert a Date String

Cannot Format Object as a Date in Java

Question:

How can a date in the format "2012-11-17T00:00:00.000-05:00" be converted into "mm/yyyy" in Java?

Error Encountered:

When attempting to use DateFormat.format directly on the string representation of the date, an exception is thrown:

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

Solution:

The key is to recognize that DateFormat.format works specifically with Date values, not string representations of dates. Therefore, the following two-step approach should be used:

  1. Parse the input string into a Date object:

    <code class="java">DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX", Locale.US);
    Date date = inputFormat.parse(inputText);</code>
    Copy after login
  2. Format the Date object into the desired output format:

    <code class="java">DateFormat outputFormat = new SimpleDateFormat("MM/yyyy", Locale.US);
    String outputText = outputFormat.format(date);</code>
    Copy after login

Example Usage:

<code class="java">String inputText = "2012-11-17T00:00:00.000-05:00";
String outputText = new SimpleDateFormat("MM/yyyy", Locale.US).format(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX", Locale.US).parse(inputText));</code>
Copy after login

By following these steps, the date string can be converted to the desired "mm/yyyy" format without encountering the Cannot format given Object as a Date exception.

The above is the detailed content of How to Convert a Date String \'2012-11-17T00:00:00.000-05:00\' to \'mm/yyyy\' Format in Java?. For more information, please follow other related articles on the PHP Chinese website!

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