Skip to content

Commit 75430b9

Browse files
committed
add calc age test
1 parent 37e291b commit 75430b9

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package com.baeldung.date;
2+
3+
import java.text.DateFormat;
4+
import java.text.SimpleDateFormat;
5+
import java.time.LocalDate;
6+
import java.time.Period;
7+
import java.util.Date;
8+
import org.joda.time.Years;
9+
10+
public class AgeCalculator {
11+
12+
public int calculateAge(LocalDate birthDate, LocalDate currentDate) {
13+
// validate inputs ...
14+
return Period.between(birthDate, currentDate)
15+
.getYears();
16+
}
17+
18+
public int calculateAgeWithJodaTime(org.joda.time.LocalDate birthDate, org.joda.time.LocalDate currentDate) {
19+
// validate inputs ...
20+
Years age = Years.yearsBetween(birthDate, currentDate);
21+
return age.getYears();
22+
}
23+
24+
public int calculateAgeWithJava7(Date birthDate, Date currentDate) {
25+
// validate inputs ...
26+
DateFormat formatter = new SimpleDateFormat("yyyyMMdd");
27+
int d1 = Integer.parseInt(formatter.format(birthDate));
28+
int d2 = Integer.parseInt(formatter.format(currentDate));
29+
int age = (d2 - d1) / 10000;
30+
return age;
31+
}
32+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package com.baeldung.date;
2+
3+
import static org.junit.Assert.assertEquals;
4+
import java.text.ParseException;
5+
import java.text.SimpleDateFormat;
6+
import java.time.LocalDate;
7+
import java.util.Date;
8+
import org.junit.jupiter.api.Test;
9+
10+
public class AgeCalculatorUnitTest {
11+
AgeCalculator ageCalculator = new AgeCalculator();
12+
13+
@Test
14+
public void givenLocalDate_whenCalculateAge_thenOk() {
15+
assertEquals(10, ageCalculator.calculateAge(LocalDate.of(2008, 5, 20), LocalDate.of(2018, 9, 20)));
16+
}
17+
18+
@Test
19+
public void givenJodaTime_whenCalculateAge_thenOk() {
20+
assertEquals(10, ageCalculator.calculateAgeWithJodaTime(new org.joda.time.LocalDate(2008, 5, 20), new org.joda.time.LocalDate(2018, 9, 20)));
21+
}
22+
23+
@Test
24+
public void givenDate_whenCalculateAge_thenOk() throws ParseException {
25+
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
26+
Date birthDate = sdf.parse("2008-05-20");
27+
Date currentDate = sdf.parse("2018-09-20");
28+
assertEquals(10, ageCalculator.calculateAgeWithJava7(birthDate, currentDate));
29+
}
30+
31+
}

0 commit comments

Comments
 (0)