Glyn
Glyn

Reputation: 1995

Checking for a null date before converting to java.sql.date from java.util.date

I am using Eclipse Juno, java and MySQL.

I am trying to check if the date is null before converting it to java.sql.Date prior to writing it to the DB.

The following works provided the date is not null:

java.sql.Date sqlPackIn = new java.sql.Date(dateBoxArchived.getValue().getTime());

So I am checking for null first:

//TODO check for a null date and handle it for dateBoxArchived and dateBoxPackOut
java.sql.Date sqlDateArchived = new java.sql.Date(System.currentTimeMillis());
if (dateBoxArchived.getValue() != null){
    sqlDateArchived = dateBoxArchived.getValue().getTime();
} else {
  sqlDateArchived = null;
  }

However, I am getting an error (Type mismatch can not convert from long to date) on sqlDateArchived = (dateBoxArchived.getValue().getTime());

and the recommended fix is to change it to long. I can not find any changed that resolves this.

Your help is greatly appreciated.

Regards,

Glyn

Upvotes: 1

Views: 2972

Answers (3)

Bohemian
Bohemian

Reputation: 425013

Some points:

  • you never use the initialized value of current time, so don't code it
  • you should pass the time of the existing date into the constructor
  • you need only one line

Try this:

java.sql.Date sqlDateArchived = dateBoxArchived.getValue() == null ? null : new java.sql.Date(dateBoxArchived.getValue().getTime());

Upvotes: 3

Brendan Long
Brendan Long

Reputation: 54242

Date.getTime() returns a long. Presumably your sqlDateArchived is a Date. You can't put a long in a Date. Either change sqlDateArchived to be a long, or create a new Date like:

sqlDateArchived = new Date(dateBoxArchived.getValue().getTime());

Upvotes: 1

Bimalesh Jha
Bimalesh Jha

Reputation: 1504

In your code if (dateBoxArchived.getValue() != null){ sqlDateArchived = dateBoxArchived.getValue().getTime();

convert last line to

sqlDateArchived = new Date(dateBoxArchived.getValue().getTime());`

Upvotes: 0

Related Questions