如何将java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S)格式化为日期(yyyy-MM-dd HH:mm:ss) [英] How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss)

查看:3911
本文介绍了如何将java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S)格式化为日期(yyyy-MM-dd HH:mm:ss)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这是对象Factura:

This is the object Factura:

public class Factura  implements java.io.Serializable {

 private FacturaId id;
 ...
 private boolean activo;
 private Date fecha;
}

在映射到数据库的xml中我有这个变量的代码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>

在数据库中该列 fecha DATETIME

当我从我的数据库中获得一个对象 Factura 时,我得到了这样的日期 2013-10-10 10:49:29.0 但我希望它没有 .0 (毫秒)。

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

我试过这个( factura Factura object):

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

fechaNueva 给我星期四10月10日10:49:29 CDT 2013 我只想要 2013-10-10 10:49:29 ,拜托,请帮帮我吗?

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?

非常感谢,提前。

推荐答案

由于格式,您根本不需要使用子字符串保留该信息。

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

这篇关于如何将java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S)格式化为日期(yyyy-MM-dd HH:mm:ss)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆