the value of date in database is 2011-03-19 18:49:04
Timestamp date;
ResultSet rs=smt.executeQuery("select * from posttopic where name='"+logn+"'");
while(rs.next()){
name=rs.getString(1);
title=rs.getString(2);
subject=rs.g开发者_如何学JAVAetString(3);
message=rs.getString(4);
date=rs.getTimestamp(5);
System.out.print(date);
}
the value of date the the above function is returning is 2011-03-19 18:49:04.0.
Why it is appending .0 at the end?How to remove it?
java.sql.Timestamp
(as returned by getTimestamp
) includes a nanosecond component, and its toString()
method appends that nanosecond value to the end of the String. In your case, the nanosecond value is zero (your data only has one-second precision).
Note that while java.sql.Timestamp
is a subclass of java.util.Date
, you should be careful about treating it as such. From the Javadoc:
This type is a composite of a
java.util.Date
and a separate nanoseconds value. Only integral seconds are stored in thejava.util.Date
component. The fractional seconds - the nanos - are separate. TheTimestamp.equals(Object)
method never returns true when passed an object that isn't an instance ofjava.sql.Timestamp
, because the nanos component of a date is unknown. As a result, theTimestamp.equals(Object)
method is not symmetric with respect to thejava.util.Date.equals(Object)
method. Also, the hashcode method uses the underlyingjava.util.Date
implementation and therefore does not include nanos in its computation.Due to the differences between the
Timestamp
class and thejava.util.Date
class mentioned above, it is recommended that code not viewTimestamp
values generically as an instance ofjava.util.Date
. The inheritance relationship betweenTimestamp
andjava.util.Date
really denotes implementation inheritance, and not type inheritance.
The question is about formatting the Date
/Timestamp
, not the internal precision (Date holds milliseconds). Try formatting the Timestamp
to not show the fractional seconds, use SimpleDateFormat
for example:
Timestamp date;
ResultSet rs=smt.executeQuery("select * from posttopic where name='"+logn+"'");
// Create a date formatter with pattern as required: year-month-day hour:minute:second
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
while(rs.next())
{
name=rs.getString(1);
title=rs.getString(2);
subject=rs.getString(3);
message=rs.getString(4);
date=rs.getTimestamp(5);
System.out.print(sdf.format(date)); // Format the date using the specified pattern.
}
精彩评论