gpt4 book ai didi

java - 如何在数据库中给出生产日期和最佳月份之前计算到期日期

转载 作者:行者123 更新时间:2023-11-28 23:57:12 26 4
gpt4 key购买 nike

我有一个数据库,其中包含制造日期和最佳月份之前的值,其中日期以“YYYY-MM-DD”格式给出。例如,制造日期是 2014-01-09,最好在给出的月份之前是 12 个月,或者它可能是数据库中给出的 11 个月。每当我尝试从数据库中检索日期时,它都会给出异常,因为第 2 列中的 DATE '12' 格式错误。

我试过的是

public void calculateExpiryDate(List<Item> items) {
// TODO Auto-generated method stub

List<Item> ItemList1 = new ArrayList<Item>();
String query = "select mfg_date,UseBeforeInMonths from cheese_tbl";
PreparedStatement prepStmt = null;
try {
prepStmt = con.prepareStatement(query);
} catch (SQLException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
ResultSet rs = null;
try {
rs = prepStmt.executeQuery();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

try {
while (rs.next()) {
Item i1=new Item();
java.sql.Date dbSqlDate = rs.getDate(2);
i1.setManufacturingDate(rs.getDate("mfg_date"));
i1.setManufacturingDate(rs.getDate("UseBeforeInMonths"));


ItemList.add(i1);
}
System.out.println(ItemList1);
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}




}

但这给了我错误的日期格式

谁能帮我计算产品的有效期。谢谢。

最佳答案

如果我理解正确,您想以 YYY-MM-DD 格式提供生产日期,并将时间存储到“最佳食用日期”之前的几个月。

我将该持续时间存储在一个整数中,并使用 Jodatime api(http://www.joda.org/joda-time/ 或者如果您使用 Java SE8 http://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html)计算最佳使用日期。

工作原理如下:

LocalDateTime manufacturingDate = new LocalDateTime(rs.getDate("mfg_date"));
LocalDateTime bestBefore = manufacturingDate.plusMonths(rs.getInt("UseBeforeInMonths"));

希望这对您有所帮助。

关于java - 如何在数据库中给出生产日期和最佳月份之前计算到期日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31342251/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com