When working with dates and times in Java, you often need to convert between different date formats. Java provides several ways to achieve this, including using the java.text.SimpleDateFormat
class and the java.time
package.
The java.text.SimpleDateFormat
class allows you to parse and format date and time strings using a specified pattern. Here's an example of how to convert a date string from one format to another:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatConverter {
public static void main(String[] args) {
String dateString = "2023-04-24 15:30:00";
String inputFormat = "yyyy-MM-dd HH:mm:ss";
String outputFormat = "MM/dd/yyyy hh:mm a";
try {
SimpleDateFormat inputFormatter = new SimpleDateFormat(inputFormat);
SimpleDateFormat outputFormatter = new SimpleDateFormat(outputFormat);
Date date = inputFormatter.parse(dateString);
String formattedDate = outputFormatter.format(date);
System.out.println("Input date: " + dateString);
System.out.println("Formatted date: " + formattedDate);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Using java.time Package
The java.time
package introduced in Java 8 provides a more robust and flexible way to work with dates and times. Here's an example of how to convert a LocalDateTime
object to a different format:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class DateFormatConverter {
public static void main(String[] args) {
LocalDateTime dateTime = LocalDateTime.of(2023, 4, 24, 15, 30, 0);
String inputFormat = "yyyy-MM-dd HH:mm:ss";
String outputFormat = "MM/dd/yyyy hh:mm a";
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern(inputFormat);
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern(outputFormat);
String formattedDate = dateTime.format(outputFormatter);
System.out.println("Input date: " + dateTime.format(inputFormatter));
System.out.println("Formatted date: " + formattedDate);
}
}
Both examples demonstrate how to convert date and time formats in Java, using either the SimpleDateFormat
class or the java.time
package.