Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using the date type in java

I am trying to get two dates from a SQL query, and compare them. So to compare them, I believe I will need to use the "Date" type. Here is what I am trying, I know I am getting the date from the resultSet incorrectly, but I am not sure how to do it.

Date validDate = new Date(0);
Date currentDate = new Date(0);

// query

    if (result.next()) {

    validDate  = (result.getObject("validDate")!=null)?result.getObject("validDate").toDate():"";
    currentDate = (result.getObject("currentDate")!=null)?result.getObject("currentDate").toDate():"";
}

if (currentDate > validDate) {
    //do something
}

So again, this was my attempt, but I cant seem to get it to run. Thanks in advance.

EDIT: the query has TO_CHAR(column, 'MM-DD-YYYY') on the two dates that I am getting.

like image 465
Dan Avatar asked Jan 19 '23 07:01

Dan


2 Answers

EDIT: Now you've mentioned that your query converts the date to a string, stop doing that. You'll end up reparsing it on the calling side - so why perform two conversions pointlessly? Keep string conversions to the absolute minimum - stay in the most appropriate data type wherever possible.


Original answer

You haven't shown what result is, but you probably want something like ResultSet.getDate() to fetch the date values.

Note that your comparison code won't work either because there's no > for Date - you'd need something like:

if (currentDate.after(validDate))

Or fetch the underlying number of millis:

if (currentDate.getTime() > validDate.getTime())

Additionally:

  • You can't assign "" to a Date variable - a string isn't a Date.
  • You can just call ResultSet.getDate() and check whether the returned value is null, rather than calling getObject first and then getDate()
like image 178
Jon Skeet Avatar answered Jan 25 '23 18:01

Jon Skeet


Try currentDate.after(validDate)

like image 25
Marc Van Daele Avatar answered Jan 25 '23 18:01

Marc Van Daele