大家好我正在创建一个程序,用于在确切年龄给出时查找出生日期.例如,如果一个男人的年龄是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));
}
Run Code Online (Sandbox Code Playgroud)
我的问题是如果我输入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));
Run Code Online (Sandbox Code Playgroud)
输出:18/10/1992.
| 归档时间: |
|
| 查看次数: |
2875 次 |
| 最近记录: |