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.

4 Answers 4

18

Java 8 approach of conversion:

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

And vice versa:

Timestamp timestamp = Timestamp.valueOf(date.toLocalDate().atStartOfDay());
Sign up to request clarification or add additional context in comments.

Comments

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).

Comments

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.

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.