Introduction:
In Java, parsing strings into dates can be a cumbersome task, especially when dealing with dates in different formats. This article will guide you through a reliable method for parsing dates with varying formats using the SimpleDateFormat class.
Problem:
You're receiving a string representing a date in a specific format (e.g., "dd/MM/yyyy") from a user. However, your application requires the date to be in a different format (e.g., "yyyy-MM-dd").
Solution:
1. Create SimpleDateFormat Objects:
2. Parse the Input String:
3. Reformat the Date:
Example Code:
SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM/yyyy"); SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd"); try { String inputString = "19/05/2009"; String reformattedStr = myFormat.format(fromUser.parse(inputString)); System.out.println(reformattedStr); // Output: 2009-05-19 } catch (ParseException e) { e.printStackTrace(); }
Handling Exceptions:
If the input string cannot be parsed or reformatted, a ParseException will be thrown. Handle this exception appropriately within your code.
The above is the detailed content of How Can I Reliably Parse Dates with Varying Formats in Java?. For more information, please follow other related articles on the PHP Chinese website!