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).
Related
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);
}
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);
I need to Validate Date in a specified format where both the inputs will be given only in the runtime in JTextfield and will be changing dynamically. Below is the code I have tried:
Date dd = new Date();
DateFormat df = new SimpleDateFormat(Date_format_text.getText());
try {
df.setLenient(false);
Date d1 = df.parse(Lower_date_text.getText());
System.out.println("Correct");
validator_LD.setVisible(false);
} catch (ParseException p) {
validator_LD.setText("*Not in mentioned Format '" + df.format(dd) + "'");
validator_LD.setVisible(true);
System.out.println("Wrong");
}
The above is.. i get the Date specified and the format specified from the text field and try to parse according to the specified format. If it doesn't match it will throw exception.
But this is not working properly in some cases :
If I give the Date 02/01/20'and the Format - dd/MM/YYYY where it should throw an exception since I have given the year as 20 and the format is 'YYYY' but i doesn't give exception.
Kindly help me.. Thanks in advance
First, you may want to take a look at How to Use the Focus Subsystem, paying attention to Validating Input which might help.
Second, as pointed out by #eatSleepCode, you're not actually parsing the text of the field, but are simply formatting an existing Date, so it will never throw an exception...
simple_format = new SimpleDateFormat(Date_format_text.getText());
// This is simply formatting the dates...
String ss = simple_format.format(dates);
Instead, you need to use something more like...
String test = "02/01/20";
String format = "dd/MM/yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(format);
sdf.setLenient(false);
try {
Date date = sdf.parse(test);
if (!sdf.format(date).equals(test)) {
throw new ParseException(test + " is not a valid format for " + format, 0);
}
} catch (ParseException ex) {
ex.printStackTrace();
}
What this does, is test's the parser capabilities of the formatter, but also checks the input against what the resulting parsed Date would be formatted to, if these don't match it throws a ParseException. This is the closes I've been able to get to a strict parser...
Also, YYYY used to represent the week in year, not the year...
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
}
I'm trying to access a static method in a Utils class I created:
public class Utils{
public static Date convertToDate(String dateString, String dFormat){
SimpleDateFormat dateFormat = new SimpleDateFormat(dFormat, Locale.US);
Date convertedDate;
try {
convertedDate = dateFormat.parse(dateString);
Log.i("date", "convertedDate = " + convertedDate);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
return convertedDate;
}
}
When I attempted to access this method like so:
Utils.convertToDate("03-04-2012", "mm-dd-yyyy");
I get a null pointer exception.
How could this be???
My guess is that it's not that method that's throwing the exception - but the fact that it returns null and you're using the return value, like this:
Date date = Utils.convertToDate("03-04-2012", "mm-dd-yyyy");
System.out.println(date.toString());
That's the problem with effectively swallowing exceptions and pretending nothing's wrong. Note that your format should be "MM-dd-yyyy" instead of "mm-dd-yyyy". Also note that your code would be simpler if you declared convertedDate within your try block and just returned it, instead of waiting to come out of the try block before returning.
(Having said all of this, I wouldn't have expected that code to throw an exception. It wouldn't give you the value you wanted, but it should be okay to actually parse... If you could produce a short but complete program demonstrating the problem, that would really help.)
Use this instead:
Utils.convertToDate("03-04-2012", "MM-dd-yyyy");
since mm represents the minutes, while MM represents the month.