Home > Java > javaTutorial > How to Convert a Date Object from One Format to Another Using SimpleDateFormat?

How to Convert a Date Object from One Format to Another Using SimpleDateFormat?

Barbara Streisand
Release: 2024-11-19 14:50:02
Original
433 people have browsed it

How to Convert a Date Object from One Format to Another Using SimpleDateFormat?

Converting a Date Object from One Format to Another Using SimpleDateFormat#format

To convert a date object from one format to another without using deprecated classes, utilize the SimpleDateFormat#format method.

In the example provided, you attempted to parse and format a date using SimpleDateFormat. However, you encountered an issue because parse expects a String input, not a Date object.

To correctly convert the date, follow these steps:

  1. Create SimpleDateFormat objects for both the original and target date formats.
  2. Use originalFormat.parse to parse the date string into a Date object.
  3. Use targetFormat.format to format the Date object into the desired date string.

Here is the revised code:

DateFormat originalFormat = new SimpleDateFormat("MMMM dd, yyyy", Locale.ENGLISH);
DateFormat targetFormat = new SimpleDateFormat("yyyyMMdd");
Date date = originalFormat.parse("August 21, 2012");
String formattedDate = targetFormat.format(date);
Copy after login

The above is the detailed content of How to Convert a Date Object from One Format to Another Using SimpleDateFormat?. 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