To accomplish a given task using SimpleDateFormat in Java, follow these steps:
Create a SimpleDateFormat object with the desired date/time format.
Use the format method of SimpleDateFormat to convert a Date object or a string into a formatted date/time string.
For example, let's say we want to format the current date and time in the format "yyyy-MM-dd HH:mm:ss". The following code demonstrates how to use SimpleDateFormat to accomplish this task:
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateExample {
public static void main(String[] args) {
// Create a SimpleDateFormat object with the desired format
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// Get the current date and time
Date now = new Date();
// Format the current date and time using the SimpleDateFormat object
String formattedDate = dateFormat.format(now);
// Print the formatted date and time string
System.out.println("Formatted Date: " + formattedDate);
}
}
This will output the current date and time in the desired format: "Formatted Date: 2022-10-20 13:45:27".
Asked: 2021-12-14 11:00:00 +0000
Seen: 9 times
Last updated: Jun 11 '21