Home >Java >javaTutorial >How Can I Easily Change Date Formats in Java?
Changing Date Format in Java: A Simple Guide
When working with dates in Java, it may become necessary to change the default or existing date format. This article provides a step-by-step guide on how to efficiently alter date formats in Java.
Java Date Format Conversion
The SimpleDateFormat class provides comprehensive capabilities for date formatting and parsing. To convert from one date format to another using SimpleDateFormat, follow these steps:
Define the original and desired date formats as strings:
final String OLD_FORMAT = "dd/MM/yyyy"; final String NEW_FORMAT = "yyyy/MM/dd";
Specify the initial date string in the old format:
String oldDateString = "12/08/2010";
Create a SimpleDateFormat object with the old format:
SimpleDateFormat sdf = new SimpleDateFormat(OLD_FORMAT);
Parse the old date string into a Date object:
Date d = sdf.parse(oldDateString);
Reset the SimpleDateFormat object with the new format:
sdf.applyPattern(NEW_FORMAT);
Use the modified SimpleDateFormat to format the Date object:
String newDateString = sdf.format(d); // Output: "2010/08/12"
This process allows you to convert dates between various formats effortlessly.
The above is the detailed content of How Can I Easily Change Date Formats in Java?. For more information, please follow other related articles on the PHP Chinese website!