I have a string representing a date, for example "2010.12.25". How can I control if it is of "yyyy.MM.dd" format? There is no need to check the validness of the date.
You have the Regex, in Groovy, you can just do:
boolean match = "2010.12.12" ==~ /\d{4}\.\d{2}\.\d{2}/
use SimpleDateFormat to parse() the string, handling the exception to decide if it is a valid date string. don't use regex to check a date. e.g.:
2010.30.40
2010.13.34
try {
Date.parse('yyyy.MM.dd', '2013.12.21')
} catch(java.text.ParseException p) {
println "Unparseable Date"
}
You can also use Groovy Date parsing to check the accuracy of date format.
You can check the format of the date by using a SimpleDateFormat like this, because using regex for validating date formats is a very bad practice, IMHO.
String strDate = "2010.12.25";
DateFormat df = new SimpleDateFormat("yyyy.MM.dd");
try {
Date date = df.parse(strDate);
// If it comes here, then its a valid format
} catch (ParseException pe) {
// If it comes here, then its not a valid date of this format.
}
Try to this check this with method isValid(String dateStr),
boolean isValid(String dateStr) {
Matcher matcher=
Pattern.compile("\\d{4}\\.\\d{2}\\.\\d{2}").matcher(dateStr);
return matcher.matches();
}
Try this one
String a = "2010.12.12";
System.out.println(a.matches("\\d{4}\\.\\d{2}\\.\\d{2}"));
Output will be true
Related
I have written the following code snippet:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.setLenient(false);
currentString = currentString.trim();
try{
Date date = sdf.parse(currentString);
} catch (java.text.ParseException e) {
return "";
}
I am expecting it to parse the date in format yyyy-MM-dd ie. it should parse date like 2013-10-28.
Though it is working fine, it is also parsing wrong inputs like 2013-10-28aaab. Ideally it should throw the exception when such kind of illegal date is given.
How can I restrict such illegal Date Patterns?
use a regex to match the input
something like
"/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/"
Just check the String length. BTW, you should set lenient to true, otherwise non valid dates (2013-02-31) will be allowed.
I have a date and it's supposed pattern in string.
//True
String date ="2012-10-12 12:01:10.10.150";
String pattern = "yyyy-MM-dd hh:mm:ss.SSS";
//False
String date ="2012-10-12 12:01:10.150";
String pattern = "yyyy-MM-dd hh:mm:ss";
Now,i wanted to know whether the date variable has a proper date which satisfies a given pattern in string. In the above example True/False which I shows is the expected result.
I have tried with SimpleDateFormat(if it throws ParseException),but it will not going to work for 2nd example.
public boolean isValidDate(String date, String pattern) {
if (date == null)
return false;
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
try {
dateFormat.parse(date.trim());
} catch (ParseException pe) {
return false;
}
return true;
}
I think you need to use both regex and SimpleDateFormat to achieve what you want
boolean validate(String date, String pattern) throws ParseException {
String regex = pattern.replaceAll("\\w", "\\\\d").replace(".", "\\.");
if (!date.matches(regex)) {
return false;
}
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
sdf.setLenient(false);
try {
sdf.parse(date);
} catch (Exception e) {
return false;
}
return true;
}
Use yyyy-MM-dd hh:mm:ss as the pattern for the second date.
String date = "2012-10-12 12:01:10";
String pattern = "yyyy-MM-dd hh:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
Date parse = sdf.parse(date);
The capital S stands for milliseconds which your second string doesn't have. See the API.
From the SimpleDateFormat.parse() Java doc:
...parsing does not necessarily use all characters up to the end of the
string...
This means if your date is longer that the pattern it will still produce a valid Date instance. The other way around (e.g. your second example) the pattern is longer (more detailed) that the given date string, hence it doesn't produce a Date. Use this instead for your second example:
String pattern = "yyyy-MM-dd hh:mm:ss";
I want to check if a String is in certain pattern.
for example i want to check is a String matches the pattern: 2012-02-20.
I.E: xxxx-xx-xx when x is a number.
Is it possible? someone said regular expressions.
use this regex \d{4}-\d{2}-\d{2}
for checking use:
yourString.matches(regexString);
if you want to test if the date string is a valid date, better use SimpleDateFormat to check. don't use regex for that validation, how about month is 13? date is 50? leap years?
some example:
public boolean isValidDate(String dateString) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
try {
df.parse(dateString);
return true;
} catch (ParseException e) {
return false;
}
}
You can do that with the SimpleDateFormat parse method:
final SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
boolean matchesDateFormat(String date)
{
try
{
format.parse(date);
return true;
}
catch(ParseException e)
{
return false;
}
}
Of course, if you later go on to parse the date anyway then you can skip this and just try to parse it.
You can check that the String follow the exact format of 4 digits, a dash -, 2 digits, a dash - and 2 digits with #burning_LEGION's regex. However, it doesn't check whether the String represents a valid date. You can specify 9999-99-99 and it will pass the validation.
Using SimpleDateFormat is the proper method to check that the String is a valid date and it follows a given format of representation. SimpleDateFormat, apart from formatting a date, can also be used to parse Date from String: parse(String), parse(String, ParsePosition).
By default, SimpleDateFormat is lenient, which means it will allow nonsensical dates such as 2013-025-234 to pass. Use setLenient(boolean lenient) to false will solve this problem.
However, another problem is that it will also ignore any garbage data that is after a valid date (e.g. 2012-03-23garbage#$%$#%). Setting lenient doesn't solve this problem. We need to check the last position with parse(String, ParsePosition) method.
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
// Make the parsing strict - otherwise, it is worse than regex solution
dateFormatter.setLenient(false);
Date date = null;
ParsePosition pos = new ParsePosition(0);
date = dateFormatter.parse(inputString, pos);
if (date != null && pos.getIndex() == inputString.length()) {
// These 3 points are ensured:
// - The string only contains the date.
// - The date follows the format strictly.
// - And the date is a valid one.
} else {
// Valid date but string contains other garbage
// Or the string has invalid date or garbage
}
SimpleDateFormat will allow 2013-1-5 to pass, which I think is a reasonable leniency. If you don't want this, you can do a check against the regex before plugging the String into the parse method.
You can check following code:
public void test() {
String REG_EXP = "(\\d{4}-[0,1]?\\d{1}-[0,1,2,3]?\\d{1})"; //yyyy-mm-dd formate this can not check boundary condition something like this... 1981-02-30
String REG_EXP1 = "(\\d{4}-\\d{2}-\\d{2})"; // if u just want xxxx-xx-xx where x is number
String input = "date1 1981-09-06 wrong date 9999-22-22 date2 1981-9-09 date3 1981-11-1 date4";
Pattern pattern = Pattern.compile(REG_EXP);
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
I am getting a null pointer exception when a user enters date in wrong format.
Method to convert String to Date
Date stringToDate(String dateString) {
Date returnDate = null;
if (dateString!= null && dateString.length() > 0 && isValidDate(dateString)) {
returnDate = dateFormat.parse(dateStr);
}
return returnDate;
}
and
boolean isValidDate(String date) {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Pattern datePattern = Pattern.compile("[0-9]{2}/[0-9]{2}/[0-9]{4}");
Matcher datePatternMatch = datePattern.matcher(date);
boolean datePatternMatchfound = datePatternMatch.matches();
if(date==null){
return false;
} else if(date!=null && date.length()>0){
if(datePatternMatchfound){
sdf.setLenient(false);
sdf.parse(date.trim());
}
return true;
} else {
return false;
}
}
I am just curious to know ....
1) what should be valid pattern for date?
2) if the user enters wrong date stringToDate method will certainly get failed and throw a null pointer exception. How to avoid that?
Any help would really be appreciated.
you are assuming the SimpleDateFormat(MM-dd-yyyyas the default pattern the user will input, either you should make sure your user can only enter in SimpleDateFormat, or you should make changes in isValidDate() to accept
Correct format of date representation depends entirely on your application and user locale. You can however limit the input format to a certain format and use it to parse and format the date input.
You can catch the ParseException thrown by the parse method and handle invalid cases inside your catch clause.
For example your code can be simplified to following:
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Date stringToDate(String dateString) {
try {
Date returnDate = sdf.parse(dateString);
// do something with returnDate, if necessary
return returnDate;
} catch(ParseException e) {
// Date is not valid, handle invalid cases here..
return null; // Not a good practice, you probably would throw an Exception
}
}
And you can use the same formatter to display your values in the user interface by calling sdf.format(someDate) method and getting the String representation.
One thing is that you need to be more defensive in your validation method.
In the code you have shown, you do this:
Matcher datePatternMatch = datePattern.matcher(date);
before you check whether the date String is null. Pattern.matcher(null) results in NullPointerException.
So you need to move this code within your if (date != null) conditional block.
Aside from that, I don't see a benefit in validating the date String with a regex before validating it with a DateFormat. The regex validation is not giving you any additional benefit.
The valid pattern format depends for instance on the country setting of system.
You should put the content of your isValidDate() method in a try-catch block to avoid an exception.
By using Simple date format class we can validate if the string is date or not. You need to make sure to set the setLenient(false) to the simple date format object.
If it's not set you are end up with issue by rounding values.For example, a lenient GregorianCalendar interprets MONTH == JANUARY, DAY_OF_MONTH == 32 as February 1.
Example code:
http://www.vijayakumarg.co.in/2014/04/how-to-validate-date-string-in-java.html
public static boolean validateJavaDate(String strDate)
{
/*
* Set preferred date format,
* For example MM-dd-yyyy, MM.dd.yyyy,dd.MM.yyyy etc.*/
SimpleDateFormat sdfrmt = new SimpleDateFormat("MM/dd/yyyy");
sdfrmt.setLenient(false);
/* Create Date object */
Date javaDate = null;
/* parse the string into date form */
try
{
javaDate = sdfrmt.parse(strDate);
System.out.println("Date after validation: " + javaDate);
}
/* Date format is invalid */
catch (ParseException e)
{
System.out.println("The date you provided is in an " +"invalid date format.");
return false;
}
/* Return 'true' - since date is in valid format */
return true;
}
Is there a good, strict date parser for Java? I have access to Joda-Time but I have yet to see this option. I found the "Is there a good date parser for Java" question, and while this is related it is sort of the opposite. Whereas that question was asking for a lenient, more fuzzy-logic and prone to human error parser, I would like a strict parser. For example, with both JodaTime (as far as I can tell) and simpleDateFormat, if you have a format "MM/dd/yyyy":
parse this: 40/40/4353
This becomes a valid date. I want a parser that knows that 40 is an invalid month and date. Surely some implementation of this exists in Java?
I don't see that Joda recognizes that as a valid date. Example:
strict = org.joda.time.format.DateTimeFormat.forPattern("MM/dd/yyyy")
try {
strict.parseDateTime('40/40/4353')
assert false
} catch (org.joda.time.IllegalFieldValueException e) {
assert 'Cannot parse "40/40/4353": Value 40 for monthOfYear must be in the range [1,12]' == e.message
}
As best as I can tell, neither does DateFormat with setLenient(false). Example:
try {
df = new java.text.SimpleDateFormat('MM/dd/yyyy')
df.setLenient(false)
df.parse('40/40/4353')
assert false
} catch (java.text.ParseException e) {
assert e.message =~ 'Unparseable'
}
Hope this helps!
A good way to do strict validation with DateFormat is re-formatting the parsed date and checking equality to the original string:
String myDateString = "87/88/9999";
Date myDate = dateFormat.parse(myDateString);
if (!myDateString.equals(df.format(myDate))){
throw new ParseException();
}
Works like a charm.
You can use the apache.commons.validator.routines.DateValidator to validate the date,if you do not want to use SimpleDateFormat.
Example :
public static Date validateDate(String value, String pattern) {
DateValidator validator = new DateValidator();
Date date = null;
if (pattern!=null) { //Pattern is passed
date = validator.validate(value, pattern);
} else {
date = validator.validate(value);
}
return date;
}
So if a null is returned it means that the date is not valid otherwise it's a valid date.This method is an alternative to using the SimpleDateFormat as you don't have to rely on exception being thrown to identify if it's a valid date or not.