Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

jdbc

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.

like image 936
And390 Avatar asked Feb 12 '13 12:02

And390


People also ask

Can we convert timestamp to date in Java?

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.

How do I convert timestamp to date?

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.


2 Answers

Java 8 approach of conversion:

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

And vice versa:

Timestamp timestamp = Timestamp.valueOf(date.toLocalDate().atStartOfDay());
like image 181
Vitaljok Avatar answered Oct 08 '22 10:10

Vitaljok


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

like image 3
Dave Webb Avatar answered Oct 08 '22 09:10

Dave Webb