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

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

Well, I'm having a detail using a Date, because I'm getting an Object from my DataBase and in the variable "fecha" (date) from that same object I'm getting a java.sql.Timestamp, so the formatt is with miliseconds, but i don't want the miliseconds to appear. So i need to formatt the date that I'm receiving from my DB to a new date that doesn't have miliseconds.

这是 Factura 的对象:

This is the object Factura:

public class Factura  implements java.io.Serializable {

 private FacturaId id;
 ...
 private boolean activo;
 private Date fecha;
}

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

In the xml that is mapped to the DB I have this code for that variable "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(毫秒).

And when I get an object Factura from my DB I'm getting this kind of date 2013-10-10 10:49:29.0 but I want it without the .0 (miliseconds).

我试过这个(facturaFactura 对象):

I've tried this (factura is the Factura object):

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,你能帮帮我吗?

But fechaNueva is giving me Thu Oct 10 10:49:29 CDT 2013 and I only want 2013-10-10 10:49:29, can you help me, please?

非常感谢,提前.

推荐答案

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

You do not need to use substring at all since your format doesn't hold that info.

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

相关文章