I need to remove time from a Date Object. Here is my try,
Code:
System.out.println("date " + dbDate);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("formatter.format(dbDate) " + formatter.format(dbDate));
System.out.println("final " + formatter.parse(formatter.format(dbDate)));
Output:
date 2011-12-03 23:59:59.0
formatter.format(dbDate) 2011-12-03
final Sat Dec 03 00:00:00 IST 2011
I want to the final date to display in 2011-12-03. But after conversion toString() of that Date is in different format. I am missing something. Please help.
Update:
In my application, I have two different methods to get dbDate. EXPIRY_DATE column is type of DATE.
First query uses dbDate = (java.util.Date) rs.getDate("EXPIRY_DATE");.
For this dbDate, System.out.println("date " + dbDate); gives date 2011-12-03
Second query uses dbDate = rs.getTimestamp("EXPIRY_DATE");
For this dbDate, System.out.println("date " + dbDate); gives date 2011-12-03 23:59:59.0.
This is my problem. As I thought toString() was giving problem, I didn’t mention the full problem.
Solution:
I did not have choices to avoid java.sql.Date as my application methods have multiple usages.
I tried the below and worked,
dbDate = new java.sql.Date(dbDate.getTime());
You can’t. The
java.util.Dateobject contains both the date and time. ItstoString()is also in a fixed format. If you want to represent it without time to humans, then you need to convert it to aStringlike as you already did. Or, if you intend to store it in the DB without the time (as thedbpart in the variable namedbDatesuggests), then you need to convert it tojava.sql.Date.Update as per your update, the
ResultSet#getDate()returns an instance ofjava.sql.Date, notjava.util.Date(but it is a subclass ofjava.util.Date, that’s why the unnecessary cast worked; please note that casting is not the same as converting, a real conversion would benew java.util.Date(dbDate.getTime())). As you can read in the javadoc of thetoString()method ofjava.sql.Date, it’s indeed inyyyy-MM-ddformat.So, your concrete problem is that you’re confusing
java.sql.Datewithjava.util.Dateand that you’re misgrasping the internal workings ofjava.util.Dateand been mislead by thetoString()method. Everything is working as intented.Related: