嗯,我在使用Date
时遇到了一些问题,因为我从数据库中获取一个对象,并且在该对象的变量“fecha”(日期)中获取了一个java.sql.Timestamp
,因此格式包含毫秒,但是我不希望毫秒出现。所以我需要将从数据库接收到的日期进行格式化,以获得没有毫秒的新日期。
这是Factura对象:
public class Factura implements java.io.Serializable {
private FacturaId id;
...
private boolean activo;
private Date fecha;
}
在映射到数据库的XML中,该变量“fecha”的代码如下:
<property name="fecha" type="timestamp">
<column length="19" name="fecha" not-null="true"/>
</property>
数据库中该列为 fecha DATETIME
。
当我从我的数据库中获取一个名为 Factura
的对象时,我得到这样的日期 2013-10-10 10:49:29.0
,但我想要去除毫秒部分的 .0
。
我尝试了以下操作(factura
是 Factura
对象):
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) {
...
}
但是fechaNueva
给了我Thu Oct 10 10:49:29 CDT 2013
,我只想要2013-10-10 10:49:29
,你能帮我吗?
非常感谢!
fechaNueva
放到同一个对象上...就像这样:SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String fechaStr = "2013-10-10 10:49:29.10000"; Date fechaNueva = format.parse(fechaStr); factura.setFecha(fechaNueva);
但是仅有Date fechaNueva = format.parse(fechaStr);
,我得到了错误的格式Thu Oct 10 10:49:29 CDT 2013
,而我不想要这个... - user2284257String
是正确的,但是如何将格式正确的2013-10-10 10:49:29
放入我的对象Factura
中作为Date
类型呢?这就是问题所在:factura.setFecha(fechaNueva);
,我该怎么做才能使fechaNueva
按照2013-10-10 10:49:29
格式进行格式化呢? - user2284257TableModel
中使用了Factura
对象,所以它在列“fecha”上打印出了这个:Thu Oct 10 10:49:29 CDT 2013
。 - user2284257