SimpleDateFormat to check user date input // parsing String to dates in java
Parsing Dates in Java with SimpleDateFormat
When developing user interfaces for management software, you often need to validate and transform user input before storing it in a database or file. For dates, user input typically arrives as strings, which need to be converted into Java's date objects.
The SimpleDateFormat
class from the java.text
package is one way to parse these strings into java.util.Date
objects.
Here's how you can use it effectively.
Basic Usage of SimpleDateFormat
The SimpleDateFormat
class provides a method called parse(String source)
that takes a date string and converts it into a Date
object.
Here's an example:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateParsingExample {
public static void main(String[] args) {
// Create a SimpleDateFormat object with the desired pattern
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
// Disable lenient parsing to enforce strict date validation
sdf.setLenient(false);
try {
System.out.println(sdf.parse("25/12/2007"));
// Output: Sun Dec 25 00:00:00 CET 2007
} catch (ParseException ex) {
System.err.println("Error parsing date: " + ex.getMessage());
}
try {
System.out.println(sdf.parse("34/15/2002"));
// Output: Invalid date format: Unparseable date: "34/15/2002"
} catch (ParseException ex) {
System.err.println("Invalid date format: " + ex.getMessage());
}
try {
System.out.println(sdf.parse("28/02/202"));
// Output: Sun Feb 28 00:00:00 GMT 202
} catch (ParseException ex) {
System.err.println("Invalid date format: " + ex.getMessage());
}
}
}
Key Points
- Pattern Specification: The format pattern (e.g.,
"dd/MM/yyyy"
) defines how the input string should be structured. - Strict Parsing: Use
sdf.setLenient(false)
to ensure that invalid dates (like "34/15/2002") throw aParseException
instead of being adjusted automatically. In the example, ifsetLenient
was set totrue
, the date "34/15/2002" would be parsed asThu Apr 03 00:00:00 GMT 2003
. - Input Validation: The last example is parsed correctly, however, depending on the requirements, this might not be the desired behavior.
Handling Incorrect Input Length
Sometimes, a date string might have a valid format but an incorrect length (e.g., "28/02/202").
To handle such cases, you can add custom validation logic:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class EnhancedDateParsing {
public static void main(String[] args) {
try {
System.out.println(parseDate("28/02/202"));
// Output: Invalid date format: Date with incorrect length: 28/02/202
} catch (ParseException ex) {
System.err.println("Invalid date format: " + ex.getMessage());
}
}
public static Date parseDate(String date) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
sdf.setLenient(false);
if (date.length() != 10) {
throw new ParseException("Date with incorrect length: " + date, 0);
}
return sdf.parse(date);
}
}
This approach ensures that only valid and correctly formatted date strings are parsed.