简体   繁体   English

如何使用Java从数据库中检索日期

[英]How to retrieve date from database using java

I need to retrieve the date and time from a database. 我需要从数据库中检索日期和时间。 My code correctly retrieves the date and time but when I use toString() it adds a ".0" to the end of the time. 我的代码正确检索了日期和时间,但是当我使用toString()它将在时间末尾添加一个“ .0”。 How can I avoid this? 如何避免这种情况?

IE: date on database is 2013-03-05 11:05:25 IE:数据库上的日期为2013-03-05 11:05:25

When I retrieve it and try to convert it to a String it becomes 2013-03-05 11:05:25.0 当我检索它并尝试将其转换为字符串时,它变为2013-03-05 11:05:25.0

 r.getTimestamp("mydate").toString();

Don't think about the value on the database as being a string value at all. 根本不要将数据库中的值视为字符串值。 Think of it being a point in time. 认为这是一个时间点。 (I'm assuming it really is a TIMESTAMP field or something similar.) (我假设它确实 TIMESTAMP字段或类似的字段。)

If you want to format it in a particular way, do so - but 2013-03-05 11:05:25 is the same point in time as 2013-03-05 11:05:25.0... it's just using a different string representation. 如果您想以特定方式设置格式,请执行以下操作-但2013-03-05 11:05:25与2013-03-05 11:05:25.0的时间点是相同的...它只是使用了不同的格式字符串表示形式。

Use SimpleDateFormat to display the date in any fashion you want 使用SimpleDateFormat以所需的任何方式显示日期

String output = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(r.getTimestamp("mydate"));

This should display it how you are after. 这应该显示它的状态。

EDIT: 编辑:

You have said your method is not returning the object as a timestamp or date, you need to put it into a date format first to use SimpleDateFormat : 您已经说过您的方法不会以时间戳或日期的形式返回对象,您需要首先将其放入日期格式才能使用SimpleDateFormat

DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String in = r.getTimestamp("mydate"));
Date d = sdf.parse(in);

If you want to actually remove the ".0" you could just do this. 如果要实际删除“ .0”,则可以执行此操作。 Where "s" is the string object with the extra 2 characters. 其中“ s”是具有额外2个字符的字符串对象。

s = s.substring(0, s.length() - 2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM