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
Release: 2025-01-01 01:56:10
Original
550 people have browsed it

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";
Copy after login
  1. Consider the original date string, for instance:
String oldDateString = "12/08/2010"; // Assuming August 12, 2010
Copy after login
  1. Create a SimpleDateFormat object using the original format:
SimpleDateFormat sdf = new SimpleDateFormat(OLD_FORMAT);
Copy after login
  1. Parse the original date string using this SimpleDateFormat object into a Date object:
Date d = sdf.parse(oldDateString);
Copy after login
  1. Subsequently, adapt the SimpleDateFormat object to use the new format:
sdf.applyPattern(NEW_FORMAT);
Copy after login
  1. Finally, format the Date object using the updated SimpleDateFormat object to obtain the new date string:
String newDateString = sdf.format(d);
Copy after login

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 of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template