Home > Java > javaTutorial > How to Convert a java.util.Date from \'yyyy-mm-dd\' to \'mm-dd-yyyy\' Format?

How to Convert a java.util.Date from \'yyyy-mm-dd\' to \'mm-dd-yyyy\' Format?

Susan Sarandon
Release: 2024-11-01 22:15:29
Original
864 people have browsed it

How to Convert a java.util.Date from

Convert java.util.Date from yyyy-mm-dd to mm-dd-yyyy

To transform a java.util.Date from the "yyyy-mm-dd" format to "mm-dd-yyyy," you can leverage the SimpleDateFormat class. This class enables you to customize the date and time formats based on specific patterns. Here's how you can implement it:

<code class="java">// Sample Date in the yyyy-mm-dd format
Date myDate = new SimpleDateFormat("yyyy-MM-dd").parse("2023-02-14");

// Convert to String using mm-dd-yyyy format
String mm_dd_yyyy = new SimpleDateFormat("MM-dd-yyyy").format(myDate);

// Convert the formatted String back to java.util.Date
Date convertedDate = new SimpleDateFormat("MM-dd-yyyy").parse(mm_dd_yyyy);

System.out.println("Original Date (yyyy-mm-dd): " + myDate);
System.out.println("Converted Date (mm-dd-yyyy): " + convertedDate);</code>
Copy after login

In this example, the original java.util.Date is parsed in the "yyyy-mm-dd" format and converted to a String using the "mm-dd-yyyy" format. Finally, the formatted String is parsed back to a java.util.Date object. This approach ensures that the java.util.Date retains its underlying value while providing a flexible way to display and manipulate dates in different formats.

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