Delfin
Delfin

Reputation: 607

getMonth getYear getDate giving errorneous result

I have a method to calculate the expiry date given manufacturing date of format("yyyy-MM-dd") and the months before the product could be used in int.First I tried with getYear getMonth getDate of Month class as follows I dint got errors results:

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(md.getYear(),md.getMonth(),md.getDate());
            //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());
        }
    }

But when I Quit using it and used setTime instead it solved my problem.I want to know what mistake I was making before and why things don't work that day and if any mistake(cause I was not getting any compile time errors) what is it actually.Following is the version of same code giving proper results.

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

Upvotes: 1

Views: 141

Answers (1)

SubOptimal
SubOptimal

Reputation: 22973

Your problem is that the constructor for GregorianCalendar expects the year as absolute value, but getYear() returns an offset to 1900.

A look into to the Java documentation reveals (beside that the used Date methods are all deprecated):

Date.getYear():
returns a value that is the result of subtracting 1900 from the year that contains or begins with the instant in time represented by this Date object, as interpreted in the local time zone.

GregorianCalendar:
year constructor parameter the value used to set the YEAR calendar field in the calendar

Whereas setTime(Date) used the value returned by md.getTime() which is number of milliseconds since January 1, 1970, 00:00:00 GMT.

Upvotes: 2

Related Questions