从字符串到日期的转换未在 JAVA 内发生

Conversion from String to Date Not happening in JAVA

我有英文日期以字符串格式出现,例如 2011-12-12。 我需要将它转换成日期格式,所以我尝试了:

 String assignDates="2011-12-12";
    DateFormat df = new SimpleDateFormat("YYYY-MM-dd");
    Date dates = df.parse(assignDates);
    cstmt.setDate(2,dates);

但我需要将其设置为 cstmt.setDate(2,dates); 但它在这一行中显示错误如下:

The method setDate(int, java.sql.Date) in the type PreparedStatement is not applicable for the arguments (int, java.util.Date)

完整代码为:

public String getConvertedDateToBs(String assignDates) {
        try
        {
            DateFormat df = new SimpleDateFormat("YYYY-MM-dd");
            System.out.println("yo ni chiryo"+assignDates);
        conn = DriverManager.getConnection(dbProperties.getDatabaseUrl());
        System.out.println("chiryoassignDatea");
            CallableStatement cstmt = conn.prepareCall("{? = call PCFN_LIB_ETON(?)}");
            cstmt.registerOutParameter(1,Types.VARCHAR);
            //java.sql.Types.VARBINARY
            Date dates = df.parse(assignDates);
            cstmt.setDate(2,dates);
            cstmt.executeUpdate();
            dateInBs = cstmt.getString(1);

            /*dateInBs = df.format(assignBsDate);*/
            System.out.println(dateInBs);
        }
        catch (SQLException e)
        {
          System.err.println(e.getMessage());
        }
        return dateInAd;
    }

假设您至少使用 JDBC 版本 4.2(您可能是),它比您想象的(未测试)更容易和更直接:

        LocalDate date = LocalDate.parse(assignDates);
        cstmt.setObject(2, date);

不需要 DateFormat/SimpleDateFormat,不需要 java.util.Date 也不需要 java.sql.Date。这很好,因为那些 类 有设计问题,尤其是第一个问题是出了名的麻烦。所有这些旧 类 都被认为早已过时。

而是使用 java.time 中的 LocalDate,现代 Java 日期和时间 API。现代 API 更好用。

我正在利用您的字符串 2011-12-12 采用 ISO 8601 格式这一事实,现代日期和时间 类 将这种格式解析(并打印)为默认格式,也就是说,没有任何明确的格式化程序。