我有一个数据库,其中包含制造日期的值,最好在月份之前,其中日期以“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();
}
}
但是这给了我错误的日期格式
任何人都可以帮我计算产品的有效期。 谢谢。
答案 0 :(得分:1)
如果我理解正确,您希望以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"));
希望这会有所帮助。