![](/img/trans.png)
[英]Cannot correctly format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to string
[英]How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss)
好吧,我有一个使用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
,你能帮帮我吗?
非常感谢,提前。
您根本不需要使用子字符串,因为您的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
java.sql.Timestamp 类没有格式。 它的 toString 方法生成一个带有格式的字符串。
不要将日期时间对象与可能表示其值的字符串混为一谈。 日期时间对象可以解析字符串并生成字符串,但它本身不是字符串。
首先从麻烦的旧日期时间类转换为 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" , " " );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.