java timestamp 格式化,如何将java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S)格式化为日期(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":

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.

解决方案

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值