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:
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!