MySQL datetime没有返回时间 [英] MySQL datetime not returning time

查看:128
本文介绍了MySQL datetime没有返回时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个MySQL数据库,其中包含一个包含 datetime 列的表。

I have a MySQL db with a table containing a datetime column.

但是,我无法在Java中找到一种方法来将其作为某种 Time 对象。

However, I cannot find a way in Java to return this as some sort of Time object within Java.

我可以调用 resultset.getString(Date),它将返回 datetime ,但这没有用,因为没有办法比较字符串上的日期等。

I can call resultset.getString("Date") and it will return the datetime, but this is no good as there is no way to compare dates, etc., on the string.

我也可以打电话给 resultset.getDate(Date),但这根本不会返回时间。

I can also call resultset.getDate("Date"), but this doesn't return the time at all.

推荐答案

您需要使用Thomas评论中建议的getTime()或getTimestamp()方法。举个例子......

You need to use the getTime() or getTimestamp() methods as suggested in the comment by Thomas. To give an example however...

对于你这样查询的表说: rs = stmt.executeQuery(select timeCol,dateCol,来自dateTimeTable的dateTimeCol);

Say for a table you query like this: rs = stmt.executeQuery("select timeCol, dateCol, dateTimeCol from dateTimeTable");

你可以这样做:

java.sql.Time dbSqlTime = rs.getTime(1);
java.sql.Date dbSqlDate = rs.getDate(2);
java.sql.Timestamp dbSqlTimestamp = rs.getTimestamp(3);

如果你想使用Java日期对象:

If you want to use the Java date object:

java.util.Date dbSqlTimeConverted = new java.util.Date(dbSqlTime.getTime());
java.util.Date dbSqlDateConverted = new java.util.Date(dbSqlDate.getTime());

我还会查看 JodaTime 与Java中的日期合作,让生活更加简单。

I would also check out JodaTime for working with Dates in Java, makes life much simpler.

最后,值得注意的是,有一些MySQL中Timestamp和DateTime之间的差异。即Timestamp有一个时区,服务器将在服务器的本地时间返回一个查询的时间戳(这可能很烦人)。我的建议是使用DateTime并始终将日期/时间保持在同一时区(即UTC)。请参阅 http://dev.mysql.com/doc/refman/5.0/ en / datetime.html

Finally, its worth noting that there are a few differences between Timestamp and DateTime in MySQL. Namely that Timestamp has a timezone and the server will return a queried Timestamp in the Server's local time (which can be annoying). My advice is to use DateTime and always keep dates/times in the same timezone (i.e. UTC). See http://dev.mysql.com/doc/refman/5.0/en/datetime.html

这篇关于MySQL datetime没有返回时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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