11

I have a Timestamp and Date variables and i want to compare it for equality (only date part of course). It was surprise for me that contructor Date(long) saves time part, so this code does not work correct:

date = resultSet.getDate(1);
timestamp = resultSet.getTimestamp(2);    
//...
if (date.equals(new Date (timestamp.getTime())) ...

I solve this with code like:

DateFormat dateFormat = new SimpleDateFormat ("yyyyMMdd");
if (date.equals(dateFormat.parse(dateFormat.format(timestamp)))) ...

Or i can convert timestamp to date in sql query, but i need a timestamp representation too. Is there a better way to cut a time part from Timestamp.

And390
  • 1,550
  • 2
  • 16
  • 22

4 Answers4

18

Java 8 approach of conversion:

Date date = Date.valueOf(timestamp.toLocalDateTime().toLocalDate());

And vice versa:

Timestamp timestamp = Timestamp.valueOf(date.toLocalDate().atStartOfDay());
Vitaljok
  • 594
  • 1
  • 6
  • 13
3

Using the method from this answer we get:

date = resultSet.getDate(1);
timestamp = resultSet.getTimestamp(2);    
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date);
cal2.setTimeInMillis(timestamp.getTime());
boolean sameDay = cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
                  cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR);

It's worth reading the linked answer as it talks about the shortcomings of this method with respects to timezones and so on (and some of the other answers to that question give alternate approaches which you may prefer).

Community
  • 1
  • 1
David Webb
  • 190,537
  • 57
  • 313
  • 299
1

You have three options with this one.

First is to use Yoda time and class DateTimeComparator.getDateOnlyInstance()

Second is to use commons from apache and DateUtils.isSameDay()

Third use the [Calendar] and set the time and compare the year, month and day of year only. As Dave Webb proposed.

1

Another approach is to use the "day" part of the epoch value:

Date d = new Date();
Timestamp t = new Timestamp(d.getTime());

long dateEpochDays = d.getTime() % (1000*60*60*24);
long timeStampEpochDays = t.getTime() %(1000*60*60*24);

System.out.println("date: " + dateEpochDays + " timestamp: " + timeStampEpochDays);
Dave
  • 13,518
  • 7
  • 42
  • 51