I am trying to store the expiry date in exp. The format I want to store it is "yyyy-MM-dd".I tried using SimpleDateFormat and than tried to format to get a string and than parse the string as follows:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date exp = sdf.parse(sdf.format(c.getTime()));
But result is I don't get date saved in exp as yyyy-MM-dd. I want to know given a date in particular format How do I convert it in other date format if the input itself is a date in one format and output is date is other format. I have used GregorianCalendar to getTime.
The format of manufacturing date is"yyyy-MM-dd"; I want the date to be stored in same format in exp;
public void calculateExpiryDate(List <Item> items) {
Iterator <Item> itr = items.iterator();
while (itr.hasNext()) {
Item i = itr.next();
Date md = i.getManufacturingDate();
int ubm = i.getUseBeforeMonths();
Calendar c = new GregorianCalendar();
c.setTime(md);
//System.out.println(c);
c.add(Calendar.MONTH, ubm);
Date exp = c.getTime();
i.setExpiryDate(exp);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(md + " " + ubm + " " + sdf.format(exp) + " " + " " + i.getId());
}
}
here is my code for Items:
public class Item implements Comparable<Item>{
private int id;
private String description;
private float weight;
private float price;
private Date manufacturingDate;
private int useBeforeMonths;
private Date expiryDate;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public float getWeight() {
return weight;
}
public void setWeight(float weight) {
this.weight = weight;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public Date getManufacturingDate() {
return manufacturingDate;
}
public void setManufacturingDate(Date manufacturingDate) {
this.manufacturingDate = manufacturingDate;
}
public int getUseBeforeMonths() {
return useBeforeMonths;
}
public void setUseBeforeMonths(int useBeforeMonths) {
this.useBeforeMonths = useBeforeMonths;
}
public void setExpiryDate(Date expiryDate) {
this.expiryDate = expiryDate;
}
public Date getExpiryDate() {
return expiryDate;
}
@Override
public int compareTo(Item arg0)
{
Date exp1=getExpiryDate();
Date exp2=arg0.getExpiryDate();
if(exp1.getYear()==exp2.getYear())
{
if(exp1.getMonth()==exp2.getMonth())
{
return exp2.getDate()-exp1.getDate();
}
else
return exp2.getMonth()-exp1.getMonth();
}
return exp2.getYear()-exp1.getYear();
}
}