【问题标题】:Converting a Date from a String representation to a numerical representation and back again将日期从字符串表示形式转换为数字表示形式并再次转换回来
【发布时间】:2010-09-14 16:01:33
【问题描述】:

是否有任何模式或已知方法可以将日期从字符串表示形式转换为数字表示形式,反之亦然?
背景:
我正在使用 Apache Derby 数据库作为 Java 程序的持久性。我想做这样的事情:

Select * from MyTable where date_column > 20100914154503 order by date_column DESC
// 20100914154503 = 2010-09-14 15:45:03

我的日期存储在我使用 Joda Time (https://www.joda.org/joda-time/) DateTime 对象的 java 程序中。
谢谢

【问题讨论】:

  • 那么你在数据库中有一个时间戳列,你想用一个字符串来查询它,或者你在数据库中有一个字符串列,你希望结果是一个 DateTime 对象?跨度>

标签: java database datetime derby


【解决方案1】:

我不太确定您实际上要做什么或为什么需要使用字符串,但通常您应该使用PreparedStatement。然后您可以使用java.sql.TimestampPreparedStatement 中设置日期:

DateTime date = ...;
Connection conn = ...;
PreparedStatement ps = conn.prepareStatement(
    "Select * from MyTable where date_column > ? order by date_column DESC");
ps.setTimestamp(1, new Timestamp(date.getMillis()));

【讨论】:

  • 数据库中的时间戳存储既好又高效,将时间戳存储在数字字段中不会有任何收获
【解决方案2】:

强烈考虑研究您的数据库如何管理日期和时间,因为它可能可以满足您的需求。请记住,您拥有的日期应该存储在数据库表的日期字段中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-26
    • 1970-01-01
    • 2018-03-27
    • 2016-06-30
    • 2014-07-02
    • 2012-01-06
    • 1970-01-01
    相关资源
    最近更新 更多