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?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-01 01:56:10561browse

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

Changing Date Format in Java: Transforming dd/MM/yyyy to yyyy/MM/dd

To alter the date format from dd/MM/yyyy to yyyy/MM/dd in Java, you can utilize the SimpleDateFormat class. Here's how to proceed:

  1. Define the original and new date formats as String constants:
final String OLD_FORMAT = "dd/MM/yyyy";
final String NEW_FORMAT = "yyyy/MM/dd";
  1. Consider the original date string, for instance:
String oldDateString = "12/08/2010"; // Assuming August 12, 2010
  1. Create a SimpleDateFormat object using the original format:
SimpleDateFormat sdf = new SimpleDateFormat(OLD_FORMAT);
  1. Parse the original date string using this SimpleDateFormat object into a Date object:
Date d = sdf.parse(oldDateString);
  1. Subsequently, adapt the SimpleDateFormat object to use the new format:
sdf.applyPattern(NEW_FORMAT);
  1. Finally, format the Date object using the updated SimpleDateFormat object to obtain the new date string:
String newDateString = sdf.format(d);

This approach allows you to successfully convert the date string from the original format (dd/MM/yyyy) to the desired format (yyyy/MM/dd).

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