user2284257 user2284257 - 1 year ago 78
Java Question

How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss)

Well, I'm having a detail using a

, because I'm getting an Object from my DataBase and in the variable "fecha" (date) from that same object I'm getting a
, 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.

This is the object Factura:

public class Factura implements {

private FacturaId id;
private boolean activo;
private Date 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"/>

In the Database that column is

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

I've tried this (
is the

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) {

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?

Thanks a lot, in advance.

Answer Source

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