getMonth getYear getDate给出了错误的结果

时间:2015-10-01 11:12:49

标签: java

我有一种方法来计算给定格式的生产日期(“yyyy-MM-dd”)的过期日期以及产品在int中使用之前的几个月。首先我尝试使用getYear getMonth获取Month类的getDate如下我得到了错误结果:

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

但是当我退出使用它并使用setTime而不是它解决了我的问题。我想知道我之前犯了什么错误以及为什么事情在那天不起作用以及如果有任何错误(因为我没有得到任何编译时间)错误)实际上是什么。以下是相同代码的版本,给出了正确的结果。

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

1 个答案:

答案 0 :(得分:2)

您的问题是[main] INFO net.thucydides.core.reports.junit.JUnitXMLOutcomeReport [pool-3-thread-1] INFO net.thucydides.core.reports.ReportService - 的构造函数需要将年份作为绝对值,但GregorianCalendar会将偏移量返回到1900.

查看Java文档显示(除了使用的Date方法都已弃用):

Date.getYear():
getYear()

的GregorianCalendar:
年构造函数参数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.

the value used to set the YEAR calendar field in the calendar使用setTime(Date)返回的值md.getTime()

相关问题