Home  >  Article  >  Java  >  How to Convert Dates Without Using Deprecated `SimpleDateFormat` Classes?

How to Convert Dates Without Using Deprecated `SimpleDateFormat` Classes?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-23 04:50:13340browse

How to Convert Dates Without Using Deprecated `SimpleDateFormat` Classes?

Date Conversion Without Deprecated Classes

You may encounter the need to convert a date from one format to another. However, the SimpleDateFormat class offers deprecated methods. How can we achieve this conversion without using these deprecated classes?

Solution: Employ the SimpleDateFormat#format method

To convert a date without using deprecated classes, follow these steps:

  • Create two SimpleDateFormat instances: originalFormat for the initial date format and targetFormat for the desired format.
  • Use originalFormat.parse(originalDateString) to parse the initial date string and obtain a Date object.
  • Apply targetFormat.format(date) to the Date object to obtain the converted date in the desired format.

Example:

Consider the following sample 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);  // 20120821

In this example, we parse the date "August 21, 2012" in the "MMMM dd, yyyy" format and convert it to the "yyyyMMdd" format, resulting in "20120821".

Note: Remember that SimpleDateFormat#parse takes a String as input, not a Date object.

The above is the detailed content of How to Convert Dates Without Using Deprecated `SimpleDateFormat` Classes?. 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