To convert a Java date string to a date format, you can use the following steps:
- Create a
SimpleDateFormat
object with the desired date format. - Use the
parse()
method to parse the date string into aDate
object. - Use the
format()
method to format theDate
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
No comments:
Post a Comment