0

Need help with parsing date(dateInString). I am new to parsing of date. Thanks for help

String dateInString = Commons.getString(row.getCell(1));
Date date = new Date();
if (!dateInString.equals("null") || !dateInString.equals("")) {
    DateFormat formatter = new SimpleDateFormat("dd.MM.yy");
    date = formatter.parse(dateInString);
}
java.sql.Date sDate = convertUtilToSql(date);

private java.sql.Date convertUtilToSql(Date date) {
    java.sql.Date sDate = new java.sql.Date(date.getTime());
    return sDate;
}

excel data

spt
  • 421
  • 4
  • 12
  • 27

1 Answers1

0

It seems that your if statement is not correct. It enters the parsing if the string context is not null or string is not empty. That looks wrong to me. The parsing should only happen if the dateString is not null AND doesn contain the value null AND is not an empty string.

So I guess that the part

if (!dateInString.equals("null") || !dateInString.equals("")) {
    DateFormat formatter = new SimpleDateFormat("dd.MM.yy");
    date = formatter.parse(dateInString);
}

has to be changed into something like

if (dateString!= null && !dateInString.equals("null") && !dateInString.trim().isEmpty()) {
    DateFormat formatter = new SimpleDateFormat("dd.MM.yy");
    date = formatter.parse(dateInString.trim());
}
uniknow
  • 938
  • 6
  • 5
  • null values are also inserting into database after modifying it – spt May 20 '16 at 07:27
  • What do you mean exactly by that? The original implementation doesn't seem to do anything with null as dateString. – uniknow May 20 '16 at 07:38
  • null values are getting inserted, when using if statement – spt May 20 '16 at 10:50
  • Don't see how thy would be inserted. In your original solution date is set to current date and later converted to sql date which is probably inserted in db. Anyway, a DateString with value null would could nullpointer exception in `date = formatter.parse(dateInString.trim());` so that's why is excluded null – uniknow May 20 '16 at 12:49