Last active
August 29, 2015 13:57
-
-
Save andreluisdias/9534960 to your computer and use it in GitHub Desktop.
Easy Date Util Class for Age calculations (Joda Time dependant)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you'd like to test it, create a 'main' method, with a simple static call:
DateUtil.calculateAge(someDate);