在Java中从年龄查找出生日期

阿克沙伊夫克

您好,我正在创建一个程序,用于在给出确切年龄时查找出生日期。例如,如果一个人的年龄是21岁10个月零22天(截至当前日期),我如何才能找到确切的出生日期。如果有人帮助我解决问题,我将不胜感激。

我试过的是这里。

此处的d,m和y是几天,几个月和几年的文本字段。

  private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
            int da = Integer.parseInt(d.getText());
            da = -da;
            int mo = Integer.parseInt(m.getText());
            mo = -mo;        
            int ye = Integer.parseInt(y.getText());
            ye = -ye;
            SimpleDateFormat ddd = new SimpleDateFormat("dd");
            SimpleDateFormat mmm = new SimpleDateFormat("MM");
            SimpleDateFormat yyy = new SimpleDateFormat("yyyy");
            Calendar cal = Calendar.getInstance();                       
            cal.getTime();
            cal.add(Calendar.DATE, da);
             cal.set(Integer.parseInt(yyy.format(cal.getTime())), Integer.parseInt(mmm.format(cal.getTime())), Integer.parseInt(ddd.format(cal.getTime())));
            cal.add(cal.MONTH, mo);cal.set(Integer.parseInt(yyy.format(cal.getTime())), Integer.parseInt(mmm.format(cal.getTime())), Integer.parseInt(ddd.format(cal.getTime())));
            cal.add(cal.YEAR, ye);
            System.out.println(getDate(cal));
        }

我的问题是,如果我输入21岁10个月零22天作为一个人的年龄,那么编译器给出的日期是18/12/1992,但是实际日期应该是17/10/1992。请帮我解决这个问题。

西班牙小吃

这是由Date&Time API实现的Java 8解决方案

int dobYear = 21;
int dobMonth = 10;
int dobDay = 22;

LocalDate now = LocalDate.now();
LocalDate dob = now.minusYears(dobYear)
        .minusMonths(dobMonth)
        .minusDays(dobDay);

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
System.out.println(dob.format(formatter));

输出:18/10/1992

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章