Home > Java > javaTutorial > How do I convert a java.util.Date from yyyy-mm-dd to mm-dd-yyyy format?

How do I convert a java.util.Date from yyyy-mm-dd to mm-dd-yyyy format?

Linda Hamilton
Release: 2024-11-01 13:32:02
Original
993 people have browsed it

How do I convert a java.util.Date from yyyy-mm-dd to mm-dd-yyyy format?

Converting java.util.Date Format from yyyy-mm-dd to mm-dd-yyyy

When working with dates in Java, you may need to convert between different date formats. One common conversion is from yyyy-mm-dd to mm-dd-yyyy. This can be achieved through the SimpleDateFormat class.

Understanding Date Objects
Date objects represent a specific point in time as the number of milliseconds since the Unix epoch (January 1, 1970). They do not have an inherent format.

SimpleDateFormat Class

The SimpleDateFormat class provides methods for formatting and parsing dates. To convert a date format, follow these steps:

  1. Create a SimpleDateFormat object with the desired format pattern:
<code class="java">SimpleDateFormat sm = new SimpleDateFormat("mm-dd-yyyy");</code>
Copy after login
  1. Format the Date object to a String using the formatter:
<code class="java">String strDate = sm.format(myDate);</code>
Copy after login
  1. (Optional) Parse the String back to a Date object (retains the original date value):
<code class="java">Date dt = sm.parse(strDate);</code>
Copy after login

Example Usage

<code class="java">Date myDate = new Date(); // Initialize a Date object

// Format myDate to mm-dd-yyyy
String formattedDate = new SimpleDateFormat("mm-dd-yyyy").format(myDate);

System.out.println("Original date: " + myDate);
System.out.println("Formatted date: " + formattedDate);</code>
Copy after login

Alternative Approach (Java 8 )

Java 8 introduced the new Date and Time API, which provides a more concise way to format dates using DateTimeFormatter:

<code class="java">LocalDateTime ldt = LocalDateTime.now();
String formattedDate = DateTimeFormatter.ofPattern("MM-dd-yyyy").format(ldt);</code>
Copy after login

The above is the detailed content of How do I 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