java 如何使用java从数据库中检索日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15213947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to retrieve date from database using java
提问by Daniel Morgan
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. How can I avoid this?
我需要从数据库中检索日期和时间。我的代码正确检索了日期和时间,但是当我使用toString()
它时,会在时间末尾添加一个“.0”。我怎样才能避免这种情况?
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();
回答by Jon Skeet
Don't think about the value on the database as being a stringvalue at all. Think of it being a point in time. (I'm assuming it really isa 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 timeas 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在同一时间点......它只是使用不同的字符串表示。
回答by Sean F
Use SimpleDateFormatto 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);
回答by Breavyn
If you want to actually remove the ".0" you could just do this. Where "s" is the string object with the extra 2 characters.
如果你想真正删除“.0”,你可以这样做。其中“s”是带有额外 2 个字符的字符串对象。
s = s.substring(0, s.length() - 2);