Home >Java >javaTutorial >How to Convert 'dd/MM/yyyy' to 'yyyy/MM/dd' Date Format in Java?

How to Convert 'dd/MM/yyyy' to 'yyyy/MM/dd' Date Format in Java?

Linda Hamilton
Linda HamiltonOriginal
2024-12-24 18:57:12532browse

How to Convert

Alter Date Representation in Java

Transforming date formats is a common need in Java applications. One such requirement is converting from "dd/MM/yyyy" to "yyyy/MM/dd" format.

To achieve this, leverage the SimpleDateFormat class:

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

// Source date: August 12, 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);

This code creates a new SimpleDateFormat object with the initial format ("dd/MM/yyyy") and parses the specified date into a Date object. The pattern is then modified to the desired format ("yyyy/MM/dd") before formatting the Date object to obtain the new date string.

The above is the detailed content of How to Convert 'dd/MM/yyyy' to 'yyyy/MM/dd' Date 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