Reputation: 21
I would like to make a validation for date. the date has many formats: European and American styles. Also, number, shortcut or even the month full name.
I used Date.parse()
but it's not accurate and it has many issues. For example: it doesn't pay attention to the leap year. Also, I added "35/02/2008" without giving me any exception.
I tried regular expression but all of what I found has an issue. None of them cover the whole possibilities.
Please advise!
Upvotes: 1
Views: 148
Reputation: 21
The issue that the input may come with different format as soon as my app is an analysis tool. If I wanna do it manually by splitting the date, I have to create a full class in order to check all the possibilities in all different formats. There's no full regular expression for this issue. How come?
Upvotes: 0
Reputation: 718768
Date validation does not make sense unless you are validating against a specific date format, or (carefully chosen) set of formats. To illustrate, consider this:
23/11/77
Is that a valid date? It depends!
If you are validating against "dd/MM/YY", then yes it is valid.
If you are validating against "MM/dd/YY", then no it isn't.
If you are validating against "dd/MM/YYYY", then it is valid but it doesn't mean what you think it means.
In short validating "any date" irrespective of format make no sense. The above date could be either valid or invalid, and can mean different things.
The fact that people "know" what these dates mean is worrying. In fact, when most people see a date, they interpret according to their own cultural norms ... without realizing that most dates are ambiguous if the format is not specified / agreed.
Upvotes: 1
Reputation: 3057
If you are using java 8 then you dont need joda. There is an in-build API LocalDateTime similarly for UTC also there is an API.
Upvotes: 0
Reputation: 1799
If you don't want (or aren't allowed) to use third-party libraries and prefer having manual control over validations, split the string using "/" as separators, then making conditions for all needed cases:
String pattern = "yyyy/MM/dd";
DateFormat df = new SimpleDateFormat(pattern);
String strDate = df.format(date);
String[] arrDate = strDate.split("/");
int year = Integer.parseInt(arrDate[0]);
int month = Integer.parseInt(arrDate[1]);
int day = Integer.parseInt(arrDate[2]);
if (month == 2 && day > 28) {
System.out.println("February has 28 days!");
}
// etc ...
Upvotes: 0
Reputation: 12992
You should have a look at the Joda Time library: http://www.joda.org/joda-time/userguide.html#Input_and_Output
For example, you can create a DateTimeFormatter, and parse some text using it:
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyyMMdd");
DateTime dt = fmt.parseDateTime(strInputDateTime);
The library allows for constructing complex date time patterns and it has knowledge of leap years etc.
Upvotes: 1