Home > Java > javaTutorial > How Can I Change Date Formats in Java?

How Can I Change Date Formats in Java?

DDD
Release: 2024-12-13 19:03:10
Original
988 people have browsed it

How Can I Change Date Formats in Java?

Altering Date Formats in Java

In Java, manipulating date formats is crucial for various scenarios. One common requirement is to convert dates from one format to another. Consider the task of changing the date format from "dd/MM/yyyy" to "yyyy/MM/dd."

The solution utilizes Java's powerful SimpleDateFormat class to convert between formats. Here's a step-by-step approach to achieve this conversion:

  1. Define the initial and target date formats.
  2. Parse the date string in the old format using SimpleDateFormat.
  3. Create a new SimpleDateFormat object with the target format.
  4. Convert the original date to the desired format using the target SimpleDateFormat.

For example, to convert the date string "12/08/2010" from "dd/MM/yyyy" to "yyyy/MM/dd," you can use the following code:

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

// 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);
Copy after login

This code snippet accurately converts the given date string in the old format to the desired format. Such conversion is essential for standardizing date representations, interfacing with different data sources, and manipulating dates in a flexible manner.

The above is the detailed content of How Can I Change Date Formats in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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