Skip to content

Instantly share code, notes, and snippets.

@andreluisdias
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andreluisdias/9534960 to your computer and use it in GitHub Desktop.
Save andreluisdias/9534960 to your computer and use it in GitHub Desktop.
Easy Date Util Class for Age calculations (Joda Time dependant)
package br.com.andreluisdias.examples.date;
import org.joda.time.Days;
import org.joda.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
/**
* DATE UTIL CLASS.
*
* @author Andre Luis de Oliveira Dias
* @date 28/01/2014
*/
public final class DateUtil {
/**
* @return
*/
public static Date getSystemDate() {
return Calendar.getInstance().getTime();
}
/**
* Calculate the age, please.
*
* @param birthDate
* Birth Date
*
* @return
* Age
*/
public static int calculateAge(Date birthDate) {
Calendar sysdate = Calendar.getInstance();
Calendar birth = Calendar.getInstance();
birth.setTime(birthDate);
int diffDay = sysdate.get(Calendar.DAY_OF_MONTH) - birth.get(Calendar.DAY_OF_MONTH);
int diffMonth = sysdate.get(Calendar.MONTH) - birth.get(Calendar.MONTH);
int result = (sysdate.get(Calendar.YEAR) - birth.get(Calendar.YEAR)) - 1;
if (diffMonth >= 0 && diffDay >= 0 ) {
result++;
}
return (result < 0) ? 0 : result;
}
/**
* Calculate the days between the start and the end date.
*
* @param startDate
* Start date
*
* @param endDate
* Finish date
*
* @return
* Days between the start and the end date.
*/
public static int daysBetween(Date startDate, Date endDate) {
return Days.daysBetween(
new LocalDate(startDate), new LocalDate(endDate)).getDays();
}
}
@andreluisdias
Copy link
Author

If you'd like to test it, create a 'main' method, with a simple static call:

DateUtil.calculateAge(someDate);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment