Unable to convert String to Date - java

I'm unable to convert a String to a Date in Java and I just can't figure it out.
String sdate1 = "01/04/2016";
SimpleDateFormat dateformat = new SimpleDateFormat("dd/MM/yyyy");
Date date1 = dateformat.parse(sdate1);
The last line causes an error, which forces me to surround it with a try/catch.
Surrounding this with a try/catch then causes the date1 to cause an error later on when trying to print the variable. The error states 'The local variable date1 may not have been initialized'.
Date date1;
try {
date1 = dateformat.parse(sdate1);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
From some digging on the internet, I think that this suggests that the variable is failing the try. However, I cannot see how it could possibly fail.

date1 variable is not definitely assigned in your case (it will not get any value if an exception is thrown as catch clause does not assign any value to the variable), so you cannot use it later (for example, to print).
To fix this, you could give the variable some initial value:
Date date1 = null;
try {
date1 = dateformat.parse(sdate1);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (date1 != null) {
// it was parsed successfully
.. do something with it
}

All you have to do is initialize the variable, when you declare it:
Date date1 = null;

You try to use the date after the try/catch which mean you use it in different scope of the try block for that you get this error, to solve this problem you have to initialize the date for example :
private Date useDate() {
String sdate1 = "01/04/2016";
SimpleDateFormat dateformat = new SimpleDateFormat("dd/MM/yyyy");
Date date1 = null;//<<------------------initialize it by null
try {
date1 = dateformat.parse(sdate1);
} catch (ParseException ex) {
//throw the exception
}
return date1;//<<--------if the parse operation success
// then return the correct date else it will return null
}

If you are not comfortable with a try catch, throw ParseException in your method declaration. Your code should work fine.

You can init your date1 = null or move it inside the try/catch.
String sdate1 = "01/04/2016";
SimpleDateFormat dateformat = new SimpleDateFormat("dd/MM/yyyy");
try {
Date date1 = dateformat.parse(sdate1);
System.out.println(date1);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Hope this help.

Related

Why compareTo doesn't return result using dates

I have dates in String format as "yyyyMMdd"
I converted them to Dates using these two function :
The first one is converting "yyyyMMdd" to "yyyy-MM-dd"
private static String converteDate(String inputString) {
SimpleDateFormat fromUser = new SimpleDateFormat("yyyyMMdd");
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");
String reformattedStr = null;
try {
reformattedStr = myFormat.format(fromUser.parse(inputString));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return reformattedStr;
}
The second function is converting the "yyyy-MM-dd" to date type:
public static Date convertToDate(String receivedDate) throws ParseException {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = formatter.parse(receivedDate);
return date;
}
Then I need to get a sorting of dates using comparaison between dates, So I used CompareTo Function :
public int compareTo(Personne personne) {
int res = 0;
Personne other = personne;
// Conversion of Dates from String to Dates
Date otherDate = null;
try {
otherDate = convertToDate(other.getDA_PRM_CTR_ORDER());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Date entreePersonne = null;
try {
entreePersonne = convertToDate(this.DA_PRM_CTR_ORDER);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
res = entreePersonne.compareTo(otherDate);
return res;
}
This is doesn't work and it returns this
Thread.dispatchUncaughtException(Throwable) line: not available
and this
EDIT :
As #MLem said
When I debugg it doesn't convert to date fomrat et pass to the exception :
this the given trace
It's really weird because the function convertToDate retun the date format normally.
This is a NullPointerException, look at the stack trace to know where it occurs.
Note that your try/catch are hazardous, if an exception is thrown, your otherDate or entreePersonne variables will be null, which is one possible cause of your NullPointerException.
Your compareTo(Personne) should throws ParseException, or have a documented behavior in case a date is unparseable.
EDIT :
I noticed after your edit that you don't use your converteDate method, so you have an input date in yyyyMMdd format and you try to parse it with yyyy-MM-dd format, hence the ParseException.
Most likely something like other said :
your string are unparseable, so it throw silented ParseException.
Your variable are still null, no calling a method on them will throw NullPointerException.
Try to answer this : what should you do if you can't parse given string ? Do it in catch block.

Is it possible to use a string parse string to capture two different time formats?

I'm using Java 8. I want to parse a string into a time (java.util.Date object) if the string is of the form "hh:mm p" (e.g. "3:00 am") or if the string is in a military time format (e.g. "15:00"). I'm unclear as to how to write an expression to capture an either/or scenario. Right now, I'm just accounting for one of the two scenarios ...
final DateFormat dateFormat = new SimpleDateFormat("hh:mm a");
try {
final java.util.Date startDate = dateFormat.parse(session.getStartTime__c());
startTime = new Time(startDate.getTime());
} catch (ParseException e) {
LOG.error(e.getMessage(), e);
} // try
Is there a way I can rewrite the above code to capture both scenarios in one format or do I need to test the string and then use a different format string depending on what my test works out to?
Try the first, and if that doesn't work, try the second
final DateFormat dateFormat = new SimpleDateFormat("hh:mm a");
final DateFormat dateFormat2 = new SimpleDateFormat(...);
java.util.Date startDate = null;
try {
startDate = dateFormat.parse(session.getStartTime__c());
startTime = new Time(startDate.getTime());
} catch (ParseException e) {
try {
startDate = dateFormat2.parse(session.getStartTime__c());
} catch (ParseException e) {
LOG.error(e.getMessage(), e);
}
} // try

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 differentiate between parse exception and invalid date range

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
}

Categories

Resources