Home >Java >javaTutorial >How can I convert date formats without using deprecated classes?
When working with dates, it's often necessary to convert between different date formats. However, one may encounter issues when attempting to use the SimpleDateFormat class, which has several deprecated methods. To address this, a more modern approach is needed.
To convert a date from one format to another without using deprecated classes, utilize SimpleDateFormat#format as follows:
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 a date in "August 21, 2012" format and convert it to a new format of "yyyyMMdd" using SimpleDateFormat#format.
It's important to note that SimpleDateFormat#parse expects a String, not a Date object. Additionally, when parsing, ensure that the format string matches the exact format of the input string.
The above is the detailed content of How can I convert date formats without using deprecated classes?. For more information, please follow other related articles on the PHP Chinese website!