Home > Java > javaTutorial > body text

How to Convert a java.util.Date from YYYY-MM-DD to MM-DD-YYYY Format?

Linda Hamilton
Release: 2024-11-01 05:00:02
Original
646 people have browsed it

How to Convert a java.util.Date from YYYY-MM-DD to MM-DD-YYYY Format?

Converting java.util.Date from YYYY-MM-DD to MM-DD-YYYY Format

Converting a java.util.Date object from the format YYYY-MM-DD to MM-DD-YYYY can be achieved using the SimpleDateFormat class.

The SimpleDateFormat constructor requires a format pattern string that specifies the desired format of the date. The pattern string consists of a combination of letters and characters that represent date and time components. For this conversion, the following pattern string will be used:

"mm-dd-yyyy"
Copy after login

This pattern indicates that the result should be formatted as month (mm), day (dd), and year (yyyy), separated by hyphens.

Here's an example code snippet that demonstrates the conversion:

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateFormatConversionExample {

    public static void main(String[] args) {
        // Sample date in YYYY-MM-DD format
        Date date = new Date("2023-05-10");

        // Create SimpleDateFormat objects for both input and output formats
        SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat outputFormat = new SimpleDateFormat("mm-dd-yyyy");

        // Convert the date from input to output format
        String formattedDate = outputFormat.format(date);

        // Print the converted date
        System.out.println("Converted date: " + formattedDate);
    }
}
Copy after login

In this example, the input date is first formatted using the "yyyy-MM-dd" pattern. Then, the formatted date is converted to the desired "mm-dd-yyyy" pattern using the outputFormat SimpleDateFormat object. Finally, the converted date is printed to the console.

The above is the detailed content of How to Convert a java.util.Date from YYYY-MM-DD to MM-DD-YYYY Format?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!