[java] 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 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.

This is the object Factura:

public class Factura  implements java.io.Serializable {

 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"/>
</property>

In the Database that column is fecha DATETIME.

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

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

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?

Thanks a lot, in advance.

This question is related to java date timestamp simpledateformat netbeans-7.1

The answer is


A date-time object is not a String

The java.sql.Timestamp class has no format. Its toString method generates a String with a format.

Do not conflate a date-time object with a String that may represent its value. A date-time object can parse strings and generate strings but is not itself a string.

java.time

First convert from the troubled old legacy date-time classes to java.time classes. Use the new methods added to the old classes.

Instant instant = mySqlDate.toInstant() ;

Lose the fraction of a second you don't want.

instant = instant.truncatedTo( ChronoUnit.Seconds );

Assign the time zone to adjust from UTC used by Instant.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z );

Generate a String close to your desired output. Replace its T in the middle with a SPACE.

DateTimeFormatter f = DateTimeFormatter.ISO_LOCAL_DATE_TIME ;
String output = zdt.format( f ).replace( "T" , " " );

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?

Examples related to timestamp

concat yesterdays date with a specific time How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Pandas: Convert Timestamp to datetime.date Spark DataFrame TimestampType - how to get Year, Month, Day values from field? What exactly does the T and Z mean in timestamp? What does this format means T00:00:00.000Z? Swift - iOS - Dates and times in different format Convert timestamp to string Timestamp with a millisecond precision: How to save them in MySQL

Examples related to simpledateformat

How to convert an Instant to a date format? Get Date Object In UTC format in Java How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss) How to convert date to string and to date again? Java Convert GMT/UTC to Local time doesn't work as expected Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST SimpleDateFormat parse loses timezone java.text.ParseException: Unparseable date Java format yyyy-MM-dd'T'HH:mm:ss.SSSz to yyyy-mm-dd HH:mm:ss SimpleDateFormat returns 24-hour date: how to get 12-hour date?

Examples related to netbeans-7.1

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