Showing posts with label java date. Show all posts
Showing posts with label java date. Show all posts

Thursday, 18 May 2023

Java convert a date string to a date format

To convert a Java date string to a date format, you can use the following steps:

  1. Create a SimpleDateFormat object with the desired date format.
  2. Use the parse() method to parse the date string into a Date object.
  3. Use the format() method to format the Date object into a new date string with the desired format.

For example, the following code converts a date string in the format "MM/dd/yyyy" to a date string in the format "yyyy-MM-dd":

import java.text.SimpleDateFormat;

public class Main {

  public static void main(String[] args) {
    // Create a SimpleDateFormat object with the desired date format.
    SimpleDateFormat dateFormat1 = new SimpleDateFormat("MM/dd/yyyy");

    // Create a date string in the format "MM/dd/yyyy".
    String dateString1 = "05/18/2023";

    // Parse the date string into a Date object.
    Date date1 = dateFormat1.parse(dateString1);

    // Create a SimpleDateFormat object with the desired date format.
    SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd");

    // Format the Date object into a new date string with the desired format.
    String dateString2 = dateFormat2.format(date1);

    // Print the new date string.
    System.out.println(dateString2);
  }
}

The output of the above code will be the following date string:

2023-05-18