Home >Java >javaTutorial >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:
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);
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!