Home >Java >javaTutorial >How Can I Change a Date's Format in Java?

How Can I Change a Date's Format in Java?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-20 07:23:09980browse

How Can I Change a Date's Format in Java?

Edit Date Format in Java

In Java, modifying date formats is a common task. One common requirement is to convert dates from a given format, such as dd/MM/yyyy, to a different format, such as yyyy/MM/dd.

Solution:

To achieve this date format conversion, you can utilize Java's SimpleDateFormat class:

final String OLD_FORMAT = "dd/MM/yyyy";
final String NEW_FORMAT = "yyyy/MM/dd";

// Example date in old format: 12/08/2010
String oldDateString = "12/08/2010";
String newDateString;

SimpleDateFormat sdf = new SimpleDateFormat(OLD_FORMAT);
Date d = sdf.parse(oldDateString);
sdf.applyPattern(NEW_FORMAT);
newDateString = sdf.format(d);

// Output: 2010/08/12 (date in new format)

This solution creates a SimpleDateFormat object and parses the input date using the old format. Then, it applies the new format pattern and formats the date accordingly, resulting in the desired output format.

The above is the detailed content of How Can I Change a Date's Format in Java?. 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