Question
How can I convert a java.util.Date object to a String with the format 'yyyy-MM-dd HH:mm:ss' in Java?
Date date = new Date(); // Assume this is your java.util.Date object
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = sdf.format(date);
Answer
In Java, converting a `java.util.Date` object to a `String` representation is a common task, especially for logging and displaying date and time. The `SimpleDateFormat` class is helpful for formatting dates into specific string patterns.
import java.util.Date;
import java.text.SimpleDateFormat;
public class DateToStringExample {
public static void main(String[] args) {
Date date = new Date(); // Current date and time
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = sdf.format(date);
System.out.println("Formatted Date: " + dateString);
}
}
Solutions
- Use the `SimpleDateFormat` class to define the desired date format.
- Call the `format` method on a `SimpleDateFormat` instance, passing the `Date` object you want to convert.
Common Mistakes
Mistake: Forgetting to import the SimpleDateFormat class.
Solution: Ensure to include `import java.text.SimpleDateFormat;` at the beginning of your Java file.
Mistake: Using an incorrect date format string.
Solution: Double-check the format string (e.g., 'yyyy-MM-dd HH:mm:ss') to ensure it matches your requirements.
Helpers
- java.util.Date
- convert Date to String
- Java date formatting
- SimpleDateFormat example
- Java date to string conversion
- format Date in Java