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

时间:2013-10-23 14:09:12

标签: java date timestamp simpledateformat netbeans-7.1

好吧,我正在使用Date获取详细信息,因为我从我的DataBase和变量“fecha”(日期)中获取了一个Object,来自同一个对象我得到了一个{{ 1}},所以formatt是毫秒,但我不希望出现毫秒。所以我需要将我从数据库接收的日期格式化为没有毫秒数的新日期。

这是对象Factura:

java.sql.Timestamp

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

public class Factura  implements java.io.Serializable {

 private FacturaId id;
 ...
 private boolean activo;
 private Date 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(毫秒)。

我试过这个(.0factura对象):

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

非常感谢,提前。

2 个答案:

答案 0 :(得分:16)

您根本不需要使用子字符串,因为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

答案 1 :(得分:3)

日期时间对象不是字符串

java.sql.Timestamp类没有格式。它的toString方法生成一个格式的String。

不要将日期时间对象与可能代表其值的String混淆。日期时间对象可以解析字符串并生成字符串,但它本身不是字符串。

java.time

首先从有问题的旧旧日期时间类转换为java.time类。使用添加到旧类的新方法。

Instant instant = mySqlDate.toInstant() ;

失去你不想要的一秒钟。

instant = instant.truncatedTo( ChronoUnit.Seconds );

指定时区以根据Instant使用的UTC进行调整。

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

生成一个接近所需输出的字符串。用空格替换中间的T

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