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.
Timestamp class can be converted to Date class in java using the Date class which is present in Java. Util package. The constructor of the Date class receives a long value as an argument.
In Java, TimeStamp can be converted into Date using the constructor of the Date class of the java. util package. It must be noted that Date class takes an argument as a long value hence the TimeStamp object needs to be converted into long. This is done using the getTime() method of Timestamp class of the java.
Java 8 approach of conversion:
Date date = Date.valueOf(timestamp.toLocalDateTime().toLocalDate());
And vice versa:
Timestamp timestamp = Timestamp.valueOf(date.toLocalDate().atStartOfDay());
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With