How to convert String to Date in Java
The SimpleDateFormat class in Java, which belongs to the java.text package, is a powerful tool for formatting and parsing dates according to specified patterns. It provides a straightforward and flexible way to handle date and time values in various formats.
One of the key features of SimpleDateFormat is its ability to format dates. You can specify a pattern that defines how the date should be displayed. The pattern consists of a combination of specific characters that represent different elements of a date, such as the year, month, day, hour, minute, and second. For example, the pattern "yyyy-MM-dd" represents a date in the format "year-month-day", such as "2023-06-29".
Here are some common pattern characters used in SimpleDateFormat:
- "y" represents the year.
- "M" represents the month.
- "d" represents the day.
- "H" represents the hour in 24-hour format.
- "h" represents the hour in 12-hour format.
- "m" represents the minute.
- "s" represents the second.
In addition to formatting, SimpleDateFormat also allows you to parse dates. Parsing refers to the process of converting a date string into a Date object, which can be used for further manipulation or calculations. You specify a pattern that matches the structure of the date string you want to parse, and SimpleDateFormat converts it into a Date object.
String to Date conversionExample
Here's an extract of all available format patterns from the javadoc:
Convert different types of string to Date in java
One of the strengths of SimpleDateFormat is its flexibility to define custom patterns. You can create patterns that suit your specific requirements and match the desired date format. For instance, if you want to display the date as "June 29, 2023," you can create a custom pattern like "MMMM dd, yyyy".
When working with SimpleDateFormat, it's crucial to handle potential exceptions. ParseException is a checked exception that can be thrown when parsing a date string that doesn't match the specified pattern. It's important to handle this exception to manage invalid or unexpected date formats.
It's worth noting that SimpleDateFormat is not thread-safe. If you plan to use SimpleDateFormat concurrently in a multi-threaded environment, you should either synchronize access to the SimpleDateFormat instance or consider using alternative thread-safe date formatting libraries like java.time.format.DateTimeFormatter introduced in Java 8.
SimpleDateFormat provides a convenient way to format and parse dates in Java. It allows you to control the display and interpretation of date and time values by defining patterns that align with your desired format.