add calc age test

This commit is contained in:
Loredana Crusoveanu 2018-09-30 13:37:09 +03:00
parent 37e291b695
commit 75430b99f2
2 changed files with 63 additions and 0 deletions

View File

@ -0,0 +1,32 @@
package com.baeldung.date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Period;
import java.util.Date;
import org.joda.time.Years;
public class AgeCalculator {
public int calculateAge(LocalDate birthDate, LocalDate currentDate) {
// validate inputs ...
return Period.between(birthDate, currentDate)
.getYears();
}
public int calculateAgeWithJodaTime(org.joda.time.LocalDate birthDate, org.joda.time.LocalDate currentDate) {
// validate inputs ...
Years age = Years.yearsBetween(birthDate, currentDate);
return age.getYears();
}
public int calculateAgeWithJava7(Date birthDate, Date currentDate) {
// validate inputs ...
DateFormat formatter = new SimpleDateFormat("yyyyMMdd");
int d1 = Integer.parseInt(formatter.format(birthDate));
int d2 = Integer.parseInt(formatter.format(currentDate));
int age = (d2 - d1) / 10000;
return age;
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.date;
import static org.junit.Assert.assertEquals;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import org.junit.jupiter.api.Test;
public class AgeCalculatorUnitTest {
AgeCalculator ageCalculator = new AgeCalculator();
@Test
public void givenLocalDate_whenCalculateAge_thenOk() {
assertEquals(10, ageCalculator.calculateAge(LocalDate.of(2008, 5, 20), LocalDate.of(2018, 9, 20)));
}
@Test
public void givenJodaTime_whenCalculateAge_thenOk() {
assertEquals(10, ageCalculator.calculateAgeWithJodaTime(new org.joda.time.LocalDate(2008, 5, 20), new org.joda.time.LocalDate(2018, 9, 20)));
}
@Test
public void givenDate_whenCalculateAge_thenOk() throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
Date birthDate = sdf.parse("2008-05-20");
Date currentDate = sdf.parse("2018-09-20");
assertEquals(10, ageCalculator.calculateAgeWithJava7(birthDate, currentDate));
}
}