插入日期并以错误的格式获取它

Insert date and get it in wrong format

我在 table 中插入当前日期。我有一个获取当前日期的方法:

private static java.sql.Date getCurrentDate() {
        java.util.Date today = new java.util.Date();
        return new java.sql.Date(today.getTime());
     }

或者在某些情况下,我从字符串格式的来源中获取日期,例如2016-10-12 然后我用 action.setTodayInfo(session, getCurrentDate()); 调用这个方法来插入 table 日期和一些布尔变量

public void setTodayInfo(HttpSession session, Date date) 
            throws SQLException, ClassNotFoundException {

        System.out.println("Initialize today's info...");

        String sq = "INSERT INTO IsSELECTED (date, morning, noon, night) VALUES (?, ?, ?, ?)";

    try {       
        Class.forName(typeDB);
        c = DriverManager.getConnection(path);            
        stm = c.prepareStatement(sq);

        PreparedStatement stm = c.prepareStatement(sq);

        stm.setDate(1, date);
        stm.setBoolean(2, FALSE);
        stm.setBoolean(3, FALSE);
        stm.setBoolean(4, FALSE);

        int rowsAffected = stm.executeUpdate();

    } catch (SQLException e) { 
    System.out.println(e.getMessage());
    } finally {
    if (stm != null) {
        stm.close();
    }
    if (c != null) {
        c.close();
    }
}          
}

当我查看 table 时,日期字段有这个 1434473268231 而不是像 2015/06/16 这样的格式的当前日期..

table格式为:

CREATE TABLE "IsSELECTED"(
       "date" DATETIME PRIMARY KEY  NOT NULL  DEFAULT (CURRENT_DATE) ,
       "morning" BOOL NOT NULL  DEFAULT (0) ,
       "noon" BOOL NOT NULL  DEFAULT (0) ,
       "night" BOOL NOT NULL  DEFAULT (0) 
 )

将 1434473268231 除以 24*60*60*1000*365 得到 45,这是自 1970 年纪元开始以来的年数。

这意味着您看到的值是自 1970 年 1 月 1 日以来的毫秒数。

这应该没问题 - 通常日期值在内部存储为自某个约定的时间点以来的毫秒数。

据此:https://www.sqlite.org/datatype3.html SQLLite 确实没有 DATETIME 的特殊类型。

"Applications can chose to store dates and times in any of these formats and freely convert between formats using the built-in date and time functions."

无需担心存储日期的格式问题。数据库将只存储日期实例,您可以使用其中之一 functions 在检索时对其进行格式化。

您还可以使用 Java 使用 SimpleDateFormat

格式化检索日期