This is the code what I have done but the date is not getting stored in the same format as the manufacturing date in the database (yyyy-MM-dd)
This calculates the expiry date for the Item:
public void calculateExpiryDate(List<Item> items)//to calculate expiry date
{
System.out.println("Calculate expiry");
try
{// to get the data one by one and calculate its expiry date
for(Item ob : items)
{
Item i1 = (Item)ob;
Date dd = (Date)i1.getManufacturingDate();
int m = i1.getUseBeforeMonths();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String date = sdf.format(dd);
String d[] = date.split("-");
d[1]=String.valueOf(Integer.parseInt(d[1])+m);
// loop to calculate expiry date
while(Integer.parseInt(d[1])>12)
{
d[1] = String.valueOf(Integer.parseInt(d[1])-12);
d[0] = String.valueOf(Integer.parseInt(d[0])+1);
}
String d1 =d[0]+"-"+d[1]+"-"+d[2];
Date dt = (Date)sdf.parse(d1);//converting string into date
i1.setExpiryDate(dt);//setting the expiry date into the database
System.out.println(i1.getExpiryDate());
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
A Date
does not have a format, since it is a time measured since 1970. If we are speaking about format, then we speak about how date is displayed, which is a different issue. Naturally, you need to change the format of "yyyy-mm-dd"
to "yyyy-MM-dd"
, but, again: 1st July 2015 is the same date as 2015-07-01. The difference is being on the way it is displayed. Needless to say, a huge part of your code is not needed. You just need to create a date from the String, do whatever you need to do and then display the date in your preferred format.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.