'How can I generate age automatically when a date is selected from jdatechooser
private void formWindowActivated(java.awt.event.WindowEvent evt) {
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
int YearNow = Integer.parseInt(sdf.format(d));
int YearBD = Integer.parseInt(sdf.format(visitordob.getDate()));
int Bd = YearNow - YearBD;
jLabel.setText(Bd);
}
Solution 1:[1]
You can use LocalDate and Period.between(). Just remember to import them from java.time:
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
Date date = formatter.parse(dob);
//Converting obtained Date object to LocalDate object
Instant instant = date.toInstant();
ZonedDateTime zone = instant.atZone(ZoneId.systemDefault());
LocalDate givenDate = zone.toLocalDate();
//Calculating the difference between given date to current date.
Period period = Period.between(givenDate, LocalDate.now());
System.out.print("Age: " + period.getYears());
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | David Velasquez |
