How to differentiate between parse exception and invalid date range - java

I have this simple program I've written
try{
SimpleDateFormat sdf = new SimpleDateFormat("M/dd/yyyy");
sdf.setLenient(false);
//Date date = sdf.parse("1/14/1999"); Apologies for confusion
Date date = sdf.parse(request.getParameter("selectedDate"));
}catch(ParseException ex){
ex.printStackTrace();
}
From what I understand a ParseException will be thrown if the date is out of range or the format given is wrong. I want to be able to tell them apart. How can I can achieve this ?
Edit: When I said out of range I meant something like this 15/15/1999. That's why setLenient(false)

ParseException doesn't offer a reliably way of determining the cause of the exception itself. You could invoke parse twice setting lenient to true and false and checking its state in the exception block
SimpleDateFormat sdf = new SimpleDateFormat("M/dd/yyyy");
try {
sdf.setLenient(true);
Date date = sdf.parse("1/33/1999");
System.out.println("DateFormat is OK");
sdf.setLenient(false);
date = sdf.parse("1/33/1999");
} catch (ParseException ex) {
ex.printStackTrace();
if (!sdf.isLenient()) {
System.out.println("Invalid date");
} else {
System.out.println("Invalid date pattern");
}
}

format given is wrong.
By that if you mean that the format is invalid, then that throws IllegalArgumentException, see here.
But you should not have to check that, the pattern you supply is determined at compile time and you should be able to ensure that it is valid; the check should be required only if the pattern is not known at compile time.

I read the doc and see that different exceptions are thrown in the two cases, so you can differentiate based on the exception class:
try {
SimpleDateFormat sdf = new SimpleDateFormat("M/dd/yyyy");
sdf.setLenient(false);
Date date = sdf.parse("1/14/1999");
} catch (IllegalArgumentException ex) {
// format exception
} catch (ParseException ex) {
// parse exception
}

Kindly have a look at these Methods .I am not good at exceptions but maybe it gives you some help.
try{
SimpleDateFormat sdf = new SimpleDateFormat("M/dd/yyyy");
sdf.setLenient(false);
Date date = sdf.parse("1/14/1999");
}catch(ParseException ex){
ex.printStackTrace();
System.out.println(ex.toString());//get cause and message ,localized details
System.out.println(ex.etErrorOffset()); //get position of error
}

Related

Try and Catch Block getting error while running code on Hackerrank but in netbeans it runs well

I don't understand why it throws an error, I have declared Date date = null,
whatever value initialized to null in the try block is not global and I am getting an error
DateFormat input = new SimpleDateFormat("hh:mm:ss aa");
DateFormat output = new SimpleDateFormat("HH:mm:ss");
Date date=null;
try{
date = input.parse(s);
}catch(ParseException e){
}
String newDate= output.format(date);
return newDate;
Error
Exception in thread "main" java.lang.NullPointerException
at java.util.Calendar.setTime(Calendar.java:1770)
at java.text.SimpleDateFormat.format(SimpleDateFormat.java:943)
at java.text.SimpleDateFormat.format(SimpleDateFormat.java:936)
at java.text.DateFormat.format(DateFormat.java:345)
at Solution.timeConversion(Solution.java:23)
at Solution.main(Solution.java:34)
You already commented that ignoring the ParseException was the root of your problem.
I like to point out how to solve this kind of problem in similar scenarios.
Problem: You are forced to handle a checked exception like ParseException. Just wrap it like this and you will not loose any information:
try {
date = input.parse(s);
} catch (ParseException e) {
throw new RuntimeException("put even more useful context infos for debugging here...", e);
}

java.text.ParseException: Unparseable date but still the code works

I am trying to create a service that does a series of operations on a database and then returns a set of information.
Among these information there's the birthdate of a series of customers.
When I try to parse (and then format) this dates I get the error in the title.
The strange thing is that even though the exception is raised, the code still compiles and runs without problems giving me the results I expect...
This is the method:
public String getDataNascitaFormattata() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
Date data = null;
try {
data = sdf.parse(dataNascita);
dataNascita = new SimpleDateFormat("dd/MM/yyyy").format(data);
} catch (ParseException e) {
System.err.println(e);
}
return dataNascita;
}
And this is an example:
Initial birthdate: "1969-09-07 00:00:00.0"
Desired birthdate: 07/09/1969
Error: java.text.ParseException: Unparseable date: "07/09/1969"
Result (WITH the exception being thrown):
EDIT: I've already tried adding the locale but the exception is still getting thrown...
EDIT2: here is a pic that explains in a better way the situation
i guess dataNascita is already a String '07/09/1969' and that's why the parse fails but the desired value is returned and the program works.
So you are trying to parse a String into an object and then re-format it in the same format as the original String!
Please run the following snippet and check your data
String dataNascita = "1969-09-07 00:00:00.0";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
Date data = null;
try {
data = sdf.parse(dataNascita);
dataNascita = new SimpleDateFormat("dd/MM/yyyy").format(data);
} catch (ParseException e) {
System.err.println(e);
}
System.out.println(dataNascita);
dataNascita = "07/09/1969";
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
data = null;
try {
data = sdf.parse(dataNascita);
dataNascita = new SimpleDateFormat("dd/MM/yyyy").format(data);
} catch (ParseException e) {
System.err.println(e);
}
System.out.println(dataNascita);
I am assuming dataNascita is a field (which seems useless).
You catch the exception and just print it to the stderr. The programming therefore continues and returns the last value assigned to dataNascita
edit:
You most likely want to do one the following
throw an exception
catch the exception elsewhere
Assign a "n/a"-kind of value to the dataNascita
You should also wonder why you are using a field for dataNascita (assuming this is the case based on the code).

String to date issues

I'm running into a problem where I can change my String to a Date but I can't retrieve the data because it's in a try/catch block :
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM");
try {
Date date = formatter.parse(input);
System.out.println(formatter.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
Any ideas on how I can retrieve the data?
Additional info: The project is to have someone input his day and month of birth so the program can go check on an Excel sheet what his astrological sign is. Do I need to convert the input to a date or am I banging my head against a wall?
Declare your date before the try/catch:
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM");
Date date = null;
try {
date = formatter.parse(input);
System.out.println(formatter.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
Declare date outside the try-catch-block and fill it inside the block. Afterwards the data will be in the variable, or not, depending on whether and at what point the try failed. This means you'll have to be prepared that it isn't filled and check for null etc.
Date date = null;
try {
date = formatter.parse(input);
System.out.println(formatter.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
if (date != null) { doSomething(date); }
You can declare date outside the try block as in the other answers; however, since you almost certainly need a valid value to proceed anyway, you should probably just include the code for processing it in the try block as well. I.e.:
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM");
try {
Date date = formatter.parse(input);
System.out.println(formatter.format(date));
// do whatever you need with date here...
} catch (ParseException e) {
e.printStackTrace();
}

How to get an exception or any sort of feedback while parsing incorrect String to Date

I would like to parse String to Date. The problem is that if I parse the wrong date like "2009-02-40" I don't get any exception (no feedback that I passed wrong date) instead I get Date object set to "2009-01-01".
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
try {
Date result = df.parse("2009-02-40");
System.out.println(result);
} catch (ParseException e) {
e.printStackTrace();
}
How to get an exception when I pass the wrong Date like this one above?
Try following code:
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
df.setLenient(false); //note the change here
try {
Date result = df.parse("2009-02-40");
System.out.println(result);
} catch (ParseException e) {
e.printStackTrace();
}
You want to call setLenient(false) on your formater. This causes "strict" checking when parsing takes places. By default, "lenient" is "true; and then some heuristics are used that turn "garbage in" into whatever.
Probably not the best design in the world; but that is how it works.
df.parse("2009-02-40"); will throw ParseException, if the beginning of the specified string cannot be parsed.
For a strict parsing, use df.setLenient(false);

How to check if given string is of specific date format?

I want to check if a given string is in a particular dateformat. If not user should be able to throw error message.
DateTimeFormat format=DateTimeFormat.getFormat("yyyy-MM-dd");
Date d= format.parse("1990-10-");
with this input , it should give error. I tried with try and catch , but its not throwing any exception.
Use the class
http://www.gwtproject.org/javadoc/latest/com/google/gwt/i18n/shared/DateTimeFormat.html#parse(java.lang.String)
Which is in shared package.
Not the clinet package class
http://www.gwtproject.org/javadoc/latest/com/google/gwt/i18n/client/DateTimeFormat.html#parse(java.lang.String)
Use java.text.SimpleDateFormat, it throws ParseException.
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
try {
Date d= format.parse("1990-10-");
} catch (ParseException e) {
...
}

Categories

Resources