3

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();
    }   

} 
12
  • What do you exactly mean with "I want to store"? Where do you want to store this? In a java variable? On disk? Oct 1, 2015 at 10:34
  • you have to add another date formatter to get the format that you want
    – Spartan
    Oct 1, 2015 at 10:34
  • exp variable is of type: Date and when you do sdf.format(exp), nothing happens to exp. sdf.format(exp) actually formats and returns StringBuffer which you can use. Oct 1, 2015 at 10:36
  • @WimDeblauwe I want to store in java variable exp. So when setExpiry is called the instance variable expiry date in Item class of type date should be assigned value of exp in the form"yyyy-MM-dd"
    – Delfin
    Oct 1, 2015 at 10:48
  • 2
    Maybe someone should tell you, that a Date doesn't has any format (except the one in the toString implementation) ...
    – Tom
    Oct 1, 2015 at 11:02

3 Answers 3

3

If I understand correctly...

You want, inside setExpiryDate get the date as a String into the format "yyyy-MM-dd". And as a constraint, the Item.setExpiryDate doesn't want to care about any SimpleDateFormat.

A solution is to use a kind of decorator pattern to redefine the string representation of a date.

public final class ExpirationDate extends Date {
    private final SimpleDateFormat formatter;

    public ExpirationDate(Date origin) {
        super(origin.getTime());
        this.formatter = new SimpleDateFormat("yyyy-MM-dd");
    }

    @Override
    public final String toString() {
        return formatter.format(this);
    }
}

And wrap your Date in a ExpirationDate every time you need this kind of representation:

Date exp = c.getTime();
i.setExpiryDate(new ExpirationDate(exp));
2
  • Reminds me of my own Version of this :D. So this is a good way to handle this situation :).
    – Tom
    Oct 1, 2015 at 12:02
  • @Spotted thanks a ton :) worked amazingly well for me
    – Delfin
    Oct 1, 2015 at 14:35
0

Try this -

import java.util.Date;
import java.util.GregorianCalendar;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.util.Calendar;

public class Temp {
  public static void main(String args[]) {
      String startDateString = "2012-03-12";
      DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
      Date startDate;
      try{
          startDate = df.parse(startDateString);

          Calendar c= new GregorianCalendar();
          c.setTime(startDate);
          c.add(Calendar.MONTH, 3);
          Date exp=c.getTime();
          SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
          String expDate = sdf.format(exp).toString();
          System.out.println(expDate);
      }catch(Exception e){
      }
  }//Body
}
2
  • expDate is of type string. I want the final output itself as Date and not string.
    – Delfin
    Oct 1, 2015 at 10:53
  • but it is not of the form I want it as, when I try to print it its not getting printed as yyyy-MM-dd. When I do the same with Manufacturind date that is md it gets printed as yyyy-MM-dd.
    – Delfin
    Oct 1, 2015 at 11:08
0

I am not sure if you manufacturing date is displayed in SDF format you mentioned. The SDF format can be used for storing date in String format

Calendar c = Calendar.getInstance();
    Date md = new Date();
    int ubm = 4;
    //System.out.println(c);
    c.setTime(md);
    c.add(Calendar.MONTH, ubm);

    Date exp = c.getTime();
    //i.setExpiryDate(exp);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    String strExpiry =  sdf.format(exp);
    System.out.println("Expiry Date in String format " + strExpiry );
    Date dtExpiry = sdf.parse(strExpiry);
    System.out.println("Expiry Date in Date format " + dtExpiry);

where as if converted to Date the result will be again the complete Date output as shown below

Expiry Date in String format 2016-02-01
Expiry Date in Date format Mon Feb 01 00:00:00 IST 2016

2
  • I want output the Date to be in format 2015-01-09 and if Input is Fri Jan 09 00:00:00 IST 2015. Both stored in type date
    – Delfin
    Oct 1, 2015 at 11:00
  • Looking at the Date class toString() implementation, don't think it will print the date in the format you expect.
    – Saurav
    Oct 1, 2015 at 11:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.