如何将java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S)格式化为日期(yyyy-MM-dd HH:mm:ss)

use*_*257 8 java timestamp date simpledateformat netbeans-7.1

好吧,我正在使用一个详细信息Date,因为我从我的DataBase和变量"fecha"(日期)中得到一个对象我得到的同一个对象java.sql.Timestamp,所以格式是毫秒,但我不希望出现毫秒.所以我需要将我从数据库接收的日期格式化为没有毫秒数的新日期.

这是Factura的对象:

public class Factura  implements java.io.Serializable {

 private FacturaId id;
 ...
 private boolean activo;
 private Date fecha;
}
Run Code Online (Sandbox Code Playgroud)

在映射到DB的xml中,我有这个变量"fecha"的代码:

<property name="fecha" type="timestamp">
  <column length="19" name="fecha" not-null="true"/>
</property>
Run Code Online (Sandbox Code Playgroud)

在列的数据库中fecha DATETIME.

当我Factura从我的数据库中获取一个对象时,我得到了这样的约会,2013-10-10 10:49:29.0但我希望它没有.0(毫秒).

我试过这个(facturaFactura对象):

try {
   SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
   Date fechaNueva = null;
   String fechaStr = factura.getFecha().toString();
   int tamaño = fechaStr.length()-2;
   fechaStr = fechaStr.substring(0, tamaño); //I get a string without the miliseconds
   fechaNueva = format.parse(fechaStr);
} catch(ParseException ex) {
   ...
}
Run Code Online (Sandbox Code Playgroud)

但是fechaNueva给我Thu Oct 10 10:49:29 CDT 2013和我只想要2013-10-10 10:49:29,你能帮助我吗?

非常感谢,提前.

Saj*_*tta 17

您根本不需要使用子字符串,因为您format不保留该信息.

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String fechaStr = "2013-10-10 10:49:29.10000";  
Date fechaNueva = format.parse(fechaStr);

System.out.println(format.format(fechaNueva)); // Prints 2013-10-10 10:49:29
Run Code Online (Sandbox Code Playgroud)