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:
<code class="java">SimpleDateFormat sm = new SimpleDateFormat("mm-dd-yyyy");</code>
<code class="java">String strDate = sm.format(myDate);</code>
<code class="java">Date dt = sm.parse(strDate);</code>
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>
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>
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!