And390
And390

Reputation: 1550

convert java.sql.Timestamp to java.sql.Date

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.

Upvotes: 11

Views: 28760

Answers (4)

Dave
Dave

Reputation: 14178

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

Upvotes: 1

Vitaljok
Vitaljok

Reputation: 623

Java 8 approach of conversion:

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

And vice versa:

Timestamp timestamp = Timestamp.valueOf(date.toLocalDate().atStartOfDay());

Upvotes: 18

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.

Upvotes: 1

David Webb
David Webb

Reputation: 193696

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

Upvotes: 3

Related Questions