To convert a string to a date in Java, you can use the SimpleDateFormat
class (legacy API) or the modern java.time
API (Java 8+). Below is a detailed guide with examples for both approaches.
1. Using SimpleDateFormat
(Legacy API)
The SimpleDateFormat
class allows parsing strings into java.util.Date
objects.
Note: This API is outdated and not thread-safe. Use the modern java.time
API (recommended for new code).
Example 1: Basic Conversion
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class StringToDate {
public static void main(String[] args) {
String dateString = "2023-10-25";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date = formatter.parse(dateString);
System.out.println(date); // Output: Wed Oct 25 00:00:00 GMT 2023
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Example 2: Custom Date Format
Parse a date-time string with a specific pattern:
String dateTimeString = "25-Oct-2023 14:30:45";
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
try {
Date date = formatter.parse(dateTimeString);
System.out.println(date); // Output: Wed Oct 25 14:30:45 GMT 2023
} catch (ParseException e) {
e.printStackTrace();
}
Common Patterns:
Pattern | Description | Example |
---|---|---|
yyyy | 4-digit year | 2023 |
MM | 2-digit month | 10 (October) |
dd | 2-digit day | 25 |
HH | 24-hour hour | 14 |
mm | Minutes | 30 |
ss | Seconds | 45 |
MMM | Abbreviated month | Oct |
2. Using java.time
API (Modern, Recommended)
Java 8 introduced the java.time
package with classes like LocalDate
, LocalDateTime
, and DateTimeFormatter
.
Advantages: Immutable, thread-safe, and more intuitive.
Example 3: String to LocalDate
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class StringToDate {
public static void main(String[] args) {
String dateString = "2023-10-25";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate date = LocalDate.parse(dateString, formatter);
System.out.println(date); // Output: 2023-10-25
}
}
Example 4: String to LocalDateTime
Parse a date-time string with time components:
String dateTimeString = "2023-10-25T14:30:45";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
LocalDateTime dateTime = LocalDateTime.parse(dateTimeString, formatter);
System.out.println(dateTime); // Output: 2023-10-25T14:30:45
Example 5: Custom Pattern with Time Zone
Parse a string with a time zone:
String zonedDateTimeString = "2023-10-25 14:30:45 GMT";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z");
ZonedDateTime zonedDateTime = ZonedDateTime.parse(zonedDateTimeString, formatter);
System.out.println(zonedDateTime); // Output: 2023-10-25T14:30:45Z[GMT]
3. Handling Different Date Formats
Example 6: Parse “dd/MM/yyyy”
String dateString = "25/10/2023";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate date = LocalDate.parse(dateString, formatter);
Example 7: Parse “MMM dd, yyyy”
String dateString = "Oct 25, 2023";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd, yyyy");
LocalDate date = LocalDate.parse(dateString, formatter);
Key Notes
- Exception Handling:
SimpleDateFormat.parse()
throwsParseException
.java.time
methods throwDateTimeParseException
(unchecked).
- Time Zones:
- Use
ZonedDateTime
orOffsetDateTime
for time zone-aware parsing.
- Locale Sensitivity:
- For month names (e.g.,
Oct
), ensure theLocale
matches the input string:java DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd, yyyy", Locale.US);
Common Errors & Fixes
- Pattern Mismatch:
Ensure the pattern matches the input string exactly (e.g.,HH
for 24-hour format vs.hh
for 12-hour). - Case Sensitivity:
MM
= month (e.g., 10),mm
= minutes. - Unknown Pattern Symbols:
Use valid symbols (e.g.,yyyy
for year, notYYYY
).
Summary of Methods
API | Class | Use Case | Thread-Safe? |
---|---|---|---|
SimpleDateFormat | java.util.Date | Legacy code (Java ≤7) | ❌ |
java.time | LocalDate , LocalDateTime | Modern applications (Java 8+) | ✔️ |
Final Recommendation
Use the java.time
API (LocalDate
, LocalDateTime
, etc.) for new projects. It avoids thread-safety issues and provides better functionality.