java - getMonth getYear getDate 给出错误结果

标签 java

我有一种方法来计算给定格式(“yyyy-MM-dd”)的制造日期以及产品可以在 int 中使用之前的月份的到期日期。首先,我尝试使用 getYear getMonth getDate of Month 类,如下所示我没有得到错误结果:

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

最佳答案

你的问题是 GregorianCalendar 的构造函数期望年份为绝对值,但 getYear()返回 1900 的偏移量。

查看 Java 文档可以发现(除了使用的 Date 方法均已弃用):

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.

公历日历:
年构造函数参数the value used to set the YEAR calendar field in the calendar

setTime(Date)使用 md.getTime() 返回的值这是 number of milliseconds since January 1, 1970, 00:00:00 GMT .

关于java - getMonth getYear getDate 给出错误结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32886160/

相关文章:

java - 在 Java 中将随机字符放置在数组板上

c# - Android客户端自动寻找C#服务器

javascript 到 java 远程方法接口(interface)

java - 获取类中方法的行号和方法名称

java - 如何在 JAX-RS 中设置 HTTP 错误代码

java - 比较2个字段的elasticsearch查询(使用java)

java - Java 中通过标准输入/输出进行通信

java - 检查 ConstraintViolationException 的原因

java - 抽象类和 netbeans 的问题

java - Caliper:微观和宏观基准