How to create method for age calculation method in android - java

I want to write a method to calculate the age from the birth date, is the logic correct and how to write it in android Java:
public int calculateAge(String birthday){
// consider that birthday format is ddmmyyyy;
String today = SystemDate(ddmmyyyy);
int bDay = birthday(1,2).toInteger;
int bMonth = birthday(3,4).toInteger;
int bYear = birhtday(5,8).toInteger;
int tDay = today(1,2).toInteger;
int tMonth = today(3,4).toInteger;
int tYear = today(5,8).toInteger;
if (tMonth == bMonth){
if (tday>= bDay){
age = tYear - bYear;
else
age = tYear - bYear - 1;}
else
if (tMonth > bMonth) {
age = tYear - bYear;
else
age = tYear - bYear - 1;}
}
return age;
}

Here is my solution to the problem:
/**
* Method to extract the user's age from the entered Date of Birth.
*
* #param DoB String The user's date of birth.
*
* #return ageS String The user's age in years based on the supplied DoB.
*/
private String getAge(int year, int month, int day){
Calendar dob = Calendar.getInstance();
Calendar today = Calendar.getInstance();
dob.set(year, month, day);
int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
if (today.get(Calendar.DAY_OF_YEAR) < dob.get(Calendar.DAY_OF_YEAR)){
age--;
}
Integer ageInt = new Integer(age);
String ageS = ageInt.toString();
return ageS;
}
I used a DatePicker to get the input values required here. This method, together with the date picker, is specifically to get the user's DoB and calculate their age. A slight modification can be made to allow for String input(s) of the user's DoB, depending upon your specific implementation. The return type of String is for updating a TextView, a slight mod can be made to allow for type int output also.

This works Perfectly.....
public int getAge(int DOByear, int DOBmonth, int DOBday) {
int age;
final Calendar calenderToday = Calendar.getInstance();
int currentYear = calenderToday.get(Calendar.YEAR);
int currentMonth = 1 + calenderToday.get(Calendar.MONTH);
int todayDay = calenderToday.get(Calendar.DAY_OF_MONTH);
age = currentYear - DOByear;
if(DOBmonth > currentMonth) {
--age;
} else if(DOBmonth == currentMonth) {
if(DOBday > todayDay){
--age;
}
}
return age;
}

Here's an example android age calculation that you should be able to work from:
public int getAge (int _year, int _month, int _day) {
GregorianCalendar cal = new GregorianCalendar();
int y, m, d, a;
y = cal.get(Calendar.YEAR);
m = cal.get(Calendar.MONTH);
d = cal.get(Calendar.DAY_OF_MONTH);
cal.set(_year, _month, _day);
a = y - cal.get(Calendar.YEAR);
if ((m < cal.get(Calendar.MONTH))
|| ((m == cal.get(Calendar.MONTH)) && (d < cal
.get(Calendar.DAY_OF_MONTH)))) {
--a;
}
if(a < 0)
throw new IllegalArgumentException("Age < 0");
return a;
}

Here is the fully tested and working code
Below is an example using date picker dialog
#Override
public void onDateSet(DatePicker view, int mBirthYear, int mMonthOfYear, int mDayOfMonth)
{
mAge = year - mBirthYear;
if( (mMonthOfYear == month && day < mDayOfMonth) || ( month < mMonthOfYear) )
{
mAge--;
}
String years = getString(R.string.years);
etAge.setText(mAge+years);
}

java.time
Due to the existence of a new(er) date and time library it is not recommended to use java.util.Date and java.util.Calendar anymore. The only exception should be a situation where you have to involve considerably large amounts of legacy code.
So… here is the modern way using java.time (Java 8+).
Java
public int getAge(int year, int month, int dayOfMonth) {
return Period.between(
LocalDate.of(year, month, dayOfMonth),
LocalDate.now()
).getYears();
}
Kotlin
fun getAge(year: Int, month: Int, dayOfMonth: Int): Int {
return Period.between(
LocalDate.of(year, month, dayOfMonth),
LocalDate.now()
).years
}
Both snippets need the following imports from java.time:
import java.time.LocalDate;
import java.time.Period
See also Oracle Tutorial.
Since there's API Desugaring in Android now, there's even no/little need for a backport like
ThreeTenABP which only supported API levels 26 and above in Android.
API desugaring makes (a subset of) java.time directly available to API levels below 26 (well, not really down to version 1, but will do for most of the API levels that should be supported nowadays).

None of the posted solutions worked for me. So, I worked my own logic and got this, which works 100% for me:
Integer getAge(Integer year, Integer month, Integer day) {
Calendar dob = Calendar.getInstance();
Calendar today = Calendar.getInstance();
dob.set(year, month, day);
int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
if(month == (today.get(Calendar.MONTH)+1) && day > today.get(Calendar.DAY_OF_MONTH)) {
age--;
}
return age;
}

The below will provide you age in the most accurate way possible
public static String getAgeFromLong(String birthday) {
SimpleDateFormat sdf= new SimpleDateFormat("ddMMyyyy",Locale.ENGLISH);
Calendar dobCal=Calendar.getInstance();
dobCal.setTime(sdf.parse(birthday));
Calendar diffCal = Calendar.getInstance();
diffCal.setTimeInMillis(Calendar.getInstance().getTimeInMillis() - dobCal.getInstance().getTimeInMillis());
String ageS = "";
int age = diffCal.get(Calendar.YEAR) - 1970;
//Check if less than a year
if (age == 0) {
age = diffCal.get(Calendar.MONTH);
//Check if less than a month
if (age == 0) {
age = diffCal.get(Calendar.WEEK_OF_YEAR);
//Check if less than a week
if (age == 1) {
age = diffCal.get(Calendar.DAY_OF_YEAR);
ageS = (age - 1) + " Days";
} else {
ageS = (age - 1) + " Weeks";
}
} else {
ageS = age + " Months";
}
} else {
ageS = age + " Years";
}
return ageS;
}

Using kotlinx-datetim , also works for KMM.
The birthdate in ISO format: 2003-02-22
fun calculateAgeFromBirthdate(birthdate: String): Int {
val birthdateParts = birthdate.split("-")
val birthYear = birthdateParts[0].toInt()
val birthMonth = birthdateParts[1].toInt()
val birthDay = birthdateParts[2].toInt()
val currentMoment = Clock.System.now()
val currentDate = currentMoment.toLocalDateTime(TimeZone.currentSystemDefault()).date
val currentYear = currentDate.year
val currentMonth = currentDate.month.ordinal + 1 //add 1 because ISO moths start from 1
val currentDay = currentDate.dayOfMonth
var age = currentYear - birthYear
if (currentMonth < birthMonth || (currentMonth == birthMonth && currentDay < birthDay)) {
age--
}
return age
}

Related

Get 'N' number of consecutive weekdays from the given date

I'm currently working on a HR system and it has an option for get 10 consecutive days (working days except weekends) of leave in its leave management module. Its a J2EE application.
All I want is to get 'N' number of consecutive weekdays from the given date
Does anybody knows how to achieve this problem?
P.S : I'm not using any 3rd party libraries like JodaTime..
Here is my controller's code for single day leave application. It has nothing to do with the consecutive days thing. but posting this here to prove that i'm doing something serious..
if (action.equals("applyLeave")) {
Leave l = new Leave();
int userid = Integer.parseInt(request.getParameter("userid"));
int leavetype = Integer.parseInt(request.getParameter("leavetype"));
String from = request.getParameter("from"); // from time
String to = request.getParameter("to"); // to time
double total = Double.parseDouble(request.getParameter("total")); // total hours
String r1 = request.getParameter("rep1");
String r2 = request.getParameter("rep2");
if (r1 == null || r1.isEmpty()) {
r1 = "0";
}
if (r2 == null || r2.isEmpty()) {
r2 = "0";
}
int rep1 = Integer.parseInt(r1);
int rep2 = Integer.parseInt(r2);
String reason = request.getParameter("reason");
String date = request.getParameter("date");
l.setUser(userid);
l.setLeavetype(leavetype);
l.setDate(date);
l.setFrom(from);
l.setReason(reason);
l.setRep1(rep1);
l.setRep2(rep2);
l.setTo(to);
l.setTotal(total);
dao.saveLeave(l);
// get manager of the department
UserDao udao = (UserDao) ctx.getBean("udao");
DepartmentDao ddao = (DepartmentDao) ctx.getBean("depdao");
NotificationDao notificationDao = (NotificationDao) ctx.getBean("notificationDao");
User u = udao.getUserByUserID(userid).get(0);
int department = u.getDepartment();
Department d = ddao.getDepartmentByID(department).get(0);
int manager = d.getManager();
// save a notification for the respective manager
// insert notification
String text = u.getFirstname() + " " + u.getLastname() + " has applied for a leave";
Notification n = new Notification();
n.setUserid(manager);
n.setFk(dao.getLeaveID());
n.setType(3);
n.setText(text);
notificationDao.saveNotification(n);
PrintWriter out = res.getWriter();
res.setContentType("text/html");
Gson gson = new Gson();
JsonObject myObj = new JsonObject();
myObj.add("message", gson.toJsonTree("Successfully Inserted"));
out.println(myObj.toString());
out.close();
}
List<Date> holidays = conf.getHolidays();
List<Date> nWorkingDays = new ArrayList<>();
// get the current date without the hours, minutes, seconds and millis
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
// iterate over the dates from now and check if each day is a business day
int businessDayCounter = 0
while (businessDayCounter < n) { //You want n working days
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek != Calendar.SATURDAY && dayOfWeek != Calendar.SUNDAY && !holidays.contains(cal.getTime())) {
businessDayCounter++;
nWorkingDays.add(cal.getTime());
}
cal.add(Calendar.DAY_OF_YEAR, 1);
}
return nWorkingDays;
Adapted from this answer: https://stackoverflow.com/a/15626124/1364747
Not sure whether you require the solution in standard java (tagged with javascript namely) but I guess you could do it as follows:
int numberOfDays = 10;
// Get current date
Calendar calendar = Calendar.getInstance();
//Repeat until all consecutive weekdays consumed
while(numberOfDays >0) {
int day = calendar.get(Calendar.DAY_OF_WEEK);
if((day != Calendar.SUNDAY) && (DAY != Calendar.SATURDAY)) {
numberOfDays--;
}
calendar.add(Calendar.DAY,1);
}
// Calendar now contains the date after consuming all
// consecutive week days
return calendar;
WARNING: Haven't compiled nor run this example so might cause exceptions.

Compare two objects, and return string. But one object doesn't take parameters?

This is homework.
GOAL: I want to compare the date of two objects to decide whether my person object is an adult or not and store this in a string.
The strange thing is, all my values of date d1 are 0;
public class Date {
public int day, month, year;
public String child
Date(date d1, date d2) {
if ((d1.year - d2.year > 18) ||
((d1.year - d2.year == 18) && (d2.year> d1.year)) ||
((d1.year - d2.year == 18) && (d2.year == d1.maand) && (d2.day > d1.day))) {
child = adult;
} else {
child = child;
}
Date(int a, int b, int c) {
a = year;
b = month;
c = day;
}
Date (String birthdate) {
String pattern = "\\d{2}-\\d{2}-\\d{4}";
boolean b = birthdate.matches(pattern);
if (b) {
String[] str = birthdate.split("-");
for (String s: str)
this.day = Integer.parseInt(str[0]);
this.month = Integer.parseInt(str[1]);
this.year = Integer.parseInt(str[2]);
this.child = false;
} else {
System.out.println("Wrong format");
}
}
When I make a test, this happens:
System.out.println("D1 year = " + d1.year);
System.out.println("D1 day = " + d1.day);
System.out.println("D1 month = " + d1.month);
Result:
D1 year = 0
D1 day = 0
D1 month = 0
Why does this happen? Lets look at my other class.
My other class, where my method infoPerson is located is as following:
public static Person infoPerson() {
String name, lastname, birthdate;
Datum birthday, today;
System.out.println("Firstname:");
name = userInput();
System.out.println("Lastname:");
lastname = userInput();
System.out.println("Birthdate?:");
birthdate = userInput();
//here I send the string birthdate to my Date class
birthday = new Date(birthdate);
today = new Date(3, 7, 2013);
//Here I want to compare my two Date objects, today and birthday. This is were I got stuck, how do I do this correctly?
dateChild = new Date(today, birthday);
// here i send the new date to my Person class what consists of two strings and Data birthday
return new Gast(name, lastname, dateChild);
}
The assignment in the constructor is reversed:
Date(int a, int b, int c) {
a = year; // should be year = a;
b = month; // month = b;
c = day; // day = c;
}
Please don't use the class name same as the one defined in Java API. Date is already a class in java.util package.
Apart from that there are many compiler errors in your code:
public string child - isn't going to compile. Should be String not string.
void compareTo(date d1, date d2) - I don't know what you're trying to do here. But this too won't compile. Undefined type - date
You've declared the Datum birthday and initializing it using new Date(...). That too wouldn't work.
For some reason, I feel like you don't have any method in your class, but just a bunch of constructors. My suggestion would be - throw that code away, and start afresh.
And please don't use a bunch of integer fields to store birthdays. Use a Calendar instance instead.

Simple way to add 30 days to a date

I'm new to programming (doing a course on Computer Science) and one of the exercises is to have the program read a date and then print the next 30 days over and over until the end of the year.
Problem is, there are restrictions. I cannot use Date/Calendar classes, only the Scanner class. So I'm having some trouble getting the dates right... so the only way I've found is to use Switch and have a case for each month, but then there's the issue with the 30/31-day months and leap years. So the days are not the same.
Is there a simpler way to do it?
If you can't use date/calendar classes, then the question is aimed at getting you to do the kind of things that date/calendar classes do internally. I wouldn't be surprised to see switch statements as part of your answer. You will need to teach your implementation knows how many days are in a month, which years are leap years etc.
You could use something like this,
Main class:
public class AppMain {
public static void main(String[] args) {
MyDate initDate = new MyDate(14, 1, 2012);
printMyDate(initDate);
MyDate newDate = initDate;
do{
newDate = DateIncrementator.increaseDate(newDate, 30);
printMyDate(newDate);
}while(newDate.getYear() == initDate.getYear());
}
private static void printMyDate(MyDate date){
System.out.println("[Day: "+ date.getDay() + "][" + "[Mont: "+ date.getMonth() + "][" + "[Year: "+ date.getYear() + "]");
}
}
DateIncrementator class:
public class DateIncrementator {
private static final int[] MONTH_DAYS_NOP_LEAP_YEAR = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
public static MyDate increaseDate(MyDate date, int numberOfDays){
if(numberOfDays < 1 || numberOfDays > 30){
throw new IllegalArgumentException("numberOfDays must have a value between 1 and 30");
}
int numberDaysCurrentMonth = MONTH_DAYS_NOP_LEAP_YEAR[date.getMonth() - 1];
if(date.getMonth() == 2 && isLeapYear(date.getYear())){
numberDaysCurrentMonth++;
}
int newDay = date.getDay();
int newMonth = date.getMonth();
int newYear = date.getYear();
newDay += numberOfDays;
if(newDay > numberDaysCurrentMonth){
newDay = newDay % numberDaysCurrentMonth;
newMonth++;
}
if(newMonth > 12){
newMonth = 1;
newYear++;
}
return new MyDate(newDay, newMonth, newYear);
}
private static boolean isLeapYear(int year){
if(year % 4 != 0){
return false;
}
if(year % 100 != 100){
return true;
}
if(year % 400 == 0){
return true;
}else{
return false;
}
}
}
MyDate class:
public class MyDate {
private int day; // 1 to 31
private int month; // 1 to 12
private int year; // 0 to infinite
public MyDate(int day, int month, int year) {
this.day = day;
this.month = month;
this.year = year;
}
public int getDay() {
return day;
}
public int getMonth() {
return month;
}
public int getYear() {
return year;
}
}

How can I add business days to the current date in Java?

How can I add business days to the current date in Java?
public Calendar addBusinessDate(Calendar cal, int days) {
//
// code goes over here
//
}
Note:
It should consider weekends too.
You may want to consider using ObjectLab Kit to do the heavy lifting for you.
Assuming the requirement is simply to return the next business day when the computed date falls on a non-business day:
package bizdays.example;
import java.time.LocalDate;
import java.util.HashSet;
import net.objectlab.kit.datecalc.common.DateCalculator;
import net.objectlab.kit.datecalc.common.DefaultHolidayCalendar;
import net.objectlab.kit.datecalc.common.HolidayHandlerType;
import net.objectlab.kit.datecalc.jdk8.LocalDateKitCalculatorsFactory;
import static org.junit.Assert.assertThat;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.Matchers.equalTo;
public class BizDayTest {
private DateCalculator<LocalDate> dateCalculator;
private final LocalDate startDate = LocalDate.of(2009, 12, 23);
#Before
public void setUp() {
HashSet<LocalDate> holidays = new HashSet<LocalDate>();
holidays.add(LocalDate.of(2009, 12, 25)); // Friday
DefaultHolidayCalendar<LocalDate> holidayCalendar =
new DefaultHolidayCalendar<LocalDate>(holidays);
LocalDateKitCalculatorsFactory.getDefaultInstance()
.registerHolidays("example", holidayCalendar);
dateCalculator = LocalDateKitCalculatorsFactory.getDefaultInstance()
.getDateCalculator("example", HolidayHandlerType.FORWARD);
dateCalculator.setStartDate(startDate);
}
#Test
public void should_not_change_calendar_start_date_even_after_moving() {
assertThat(
dateCalculator.moveByBusinessDays(6).getStartDate(),
equalTo(startDate));
}
#Test
public void moveByBusinessDays_will_return_24_dec_2009_as_next_business_day() {
assertThat(
dateCalculator.moveByBusinessDays(1).getCurrentBusinessDate(),
equalTo(LocalDate.of(2009, 12, 24)));
}
#Test
public void moveByBusinessDays_will_return_28_dec_2009_as_two_business_days_later() {
assertThat(
dateCalculator.moveByBusinessDays(2).getCurrentBusinessDate(),
equalTo(LocalDate.of(2009, 12, 28)));
}
#Test
public void moveByDays_will_also_return_28_dec_2009_as_two_business_days_later() {
assertThat(
dateCalculator.moveByDays(2).getCurrentBusinessDate(),
equalTo(LocalDate.of(2009, 12, 28)));
}
#Test
public void moveByBusinessDays_will_exclude_25_26_and_27_dec_when_computing_business_days() {
assertThat(
dateCalculator.moveByBusinessDays(5).getCurrentBusinessDate(),
equalTo(LocalDate.of(2009, 12, 31)));
}
#Test
public void moveByDays_will_include_25_26_and_27_dec_when_computing_business_days() {
assertThat(
dateCalculator.moveByDays(5).getCurrentBusinessDate(),
equalTo(LocalDate.of(2009, 12, 28)));
}
}
The library defaults the working week to be from Monday to Friday, but you can change the defaults by supplying a custom WorkingWeek to DateCalculator's setWorkingWeek().
As shown in the last two examples, moveByDays() includes the weekends when moving the days, whereas moveByBusinessDays() excludes weekends.
The library also allows you to use java.util.Calendar or Joda Time's LocalDate. The examples use JDK8's java.time.LocalDate because it is the preferred way since JDK8.
Edit: Updated examples to use java.time.LocalDate
Use:
public Calendar addBusinessDate(Calendar cal, int numBusinessDays) {
int numNonBusinessDays = 0;
for(int i = 0; i < numBusinessDays; i++) {
cal.add(Calendar.DATE, 1);
/*
It's a Canadian/American custom to get the Monday (sometimes Friday) off
when a holiday falls on a weekend.
*/
for(int j = 0; j < holidays; j++) { //holidays is list of dates
if(cal.getTime() == (Date)holidays.get(j)) {
numNonBusinessDays++;
}
}
if(cal.get(Calendar.DAY_OF_WEEK) == 1 ||
cal.get(Calendar.DAY_OF_WEEK) == 7) {
numNonBusinessDays++;
}
}
if(numNonBusinessDays > 0) {
cal.add(Calendar.DATE, numNonBusinessDays);
}
return cal;
}
You'd have to populate a list of dates in order to handle holidays. There's common ones like New Years, but Thanksgiving is different between Canada & the US for instance. Also mind that holidays can fall on a weekend, so the weekend becomes a 3 day weekend.
Reference:
Calendar
Calendar Constant Values
PS: There isn't really a need to return the Calendar instance if you are updating the value as in the example. But it is valid if you want to create a separate Calendar instance, use:
public Calendar addBusinessDate(Calendar cal, int numBusinessDays) {
Calendar cal2 = Calendar.getInstance();
cal2.setTime(cal.getTime());
int numNonBusinessDays = 0;
for(int i = 0; i < numBusinessDays; i++) {
cal2.add(Calendar.DATE, 1);
/*
It's a Canadian/American custom to get the Monday (sometimes Friday) off
when a holiday falls on a weekend.
*/
for(int j = 0; j < holidays; j++) { //holidays is list of dates
if(cal2.getTime() == (Date)holidays.get(j)) {
numNonBusinessDays++;
}
}
if(cal2.get(Calendar.DAY_OF_WEEK) == 1 ||
cal2.get(Calendar.DAY_OF_WEEK) == 7) {
numNonBusinessDays++;
}
}
if(numNonBusinessDays > 0) {
cal2.add(Calendar.DATE, numNonBusinessDays);
}
return cal2;
}
Here is the modified version to find date calculation.
public Calendar algorithm2(int businessDays){
Calendar cal2 = Calendar.getInstance();
Calendar cal = Calendar.getInstance();
int totalDays= businessDays/5*7;
int remainder = businessDays % 5;
cal2.add(cal2.DATE, totalDays);
switch(cal.get(Calendar.DAY_OF_WEEK)){
case 1:
break;
case 2:
break;
case 3:
if(remainder >3)
cal2.add(cal2.DATE,2);
break;
case 4:
if(remainder >2)
cal2.add(cal2.DATE,2);
break;
case 5:
if(remainder >1)
cal2.add(cal2.DATE,2);
break;
case 6:
if(remainder >1)
cal2.add(cal2.DATE,2);
break;
case 7:
if(remainder >1)
cal2.add(cal2.DATE,1);
break;
}
cal2.add(cal2.DATE, remainder);
return cal2;
}
//supports negative numbers too.
private Calendar addBusinessDay(final Calendar cal, final Integer numBusinessDays)
{
if (cal == null || numBusinessDays == null || numBusinessDays.intValue() == 0)
{
return cal;
}
final int numDays = Math.abs(numBusinessDays.intValue());
final int dateAddition = numBusinessDays.intValue() < 0 ? -1 : 1;//if numBusinessDays is negative
int businessDayCount = 0;
while (businessDayCount < numDays)
{
cal.add(Calendar.DATE, dateAddition);
//check weekend
if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)
{
continue;//adds another day
}
//check holiday
if (isHoliday(cal))//implement isHoliday yourself
{
continue;//adds another day
}
businessDayCount++;
}
return cal;
}
public static Date addBusinessDays(Date date, int days) {
DateTime result = new DateTime(date);
result = isWeekEnd(result)
? getPreviousBusinessDate(result)
: result;
for (int i = 0; i < days; i++) {
if (isWeekEnd(result)) {
i--;
}
result = result.plusDays(1);
}
return result.toDate();
}
private static boolean isWeekEnd(DateTime dateTime) {
int dayOfWeek = dateTime.getDayOfWeek();
return dayOfWeek == DateTimeConstants.SATURDAY || dayOfWeek == DateTimeConstants.SUNDAY;
}
private static DateTime getPreviousBusinessDate(DateTime result) {
while (isWeekEnd(result)) {
result = result.minusDays(1);
}
return result;
}
Will this work? Of course, this is not handling holidays.
public static Date
addBusinessDays(Date baseDate, int
numberOfDays){
if(baseDate == null){
baseDate = new Date();
}
Calendar baseDateCal = Calendar.getInstance();
baseDateCal.setTime(baseDate);
for(int i = 0; i < numberOfDays; i++){
baseDateCal.add(Calendar.DATE,1);
if(baseDateCal.get(Calendar.DAY_OF_WEEK)
== Calendar.SATURDAY){
baseDateCal.add(Calendar.DATE,2);
}
}
return baseDateCal.getTime();
}
tl;dr
Going forward.
myLocalDate.with(
org.threeten.extra.Temporals.nextWorkingDay()
)
Going backward.
myLocalDate.with(
org.threeten.extra.Temporals.previousWorkingDay()
)
Using java.time
The Question and other Answers use the troublesome old date-time classes, now legacy, supplanted by the java.time classes.
Also, see my Answer to a similar Question.
TemporalAdjuster
In java.time, the TemporalAdjuster interface provides for classes to manipulate date-time values. Using immutable objects, a new instance is created with values based on the original.
nextWorkingDay
The ThreeTen-Extra project extend java.time with additional functionality. That includes a nextWorkingDay adjuster that skips over Saturday and Sunday days. So we can loop, incrementing a date one day at a time, and skip over any weekend days.
The LocalDate class represents a date-only value without time-of-day and without time zone.
LocalDate start = LocalDate.now( ZoneId.of( "America/Montreal" ) ) ;
int businessDaysToAdd = 13 ;
// … ensure that: ( businessDaysToAdd >= 0 )
int daysLeft = businessDaysToAdd ;
LocalDate localDate = start ;
while ( daysLeft > 0 ) {
localDate = localDate.with( Temporals.nextWorkingDay() );
daysLeft = ( daysLeft - 1 ) ; // Decrement as we go.
}
return localDate ;
Holidays
Holidays are an entirely different matter. Obviously there is no simple solution. You must either supply a list of your honored holidays, or obtain a list with which you agree.
Once you have such a list, I suggest writing your own implementation of TemporalAdjuster similar to nextWorkingDay.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
This algorithm calculates the next business date for a given date
(business days are from monday to friday in my country), you can adapt it to iterate the number of days you need to add.
public Calendar nextBusinessDate(Calendar cal) {
List<Calendar> holidays = ********
// Here get list of holidays from DB or some other service...
GregorianCalendar calCp = new GregorianCalendar();
calCp.setTime(cal.getTime());
calCp.add(Calendar.DAY_OF_MONTH, 1);
boolean isSaturday = (calCp.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY);
boolean isSunday = (calCp.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY);
boolean isHoliday = holidays.contains(calCp);
while (isSaturday || isSunday || isHoliday) {
if (isSaturday) {
calCp.add(Calendar.DAY_OF_MONTH, +2); // is saturday, make it monday
} else {
if (isSunday) {
calCp.add(Calendar.DAY_OF_MONTH, +1); // is sunday, make it monday
} else {
if (isHoliday) {
calCp.add(Calendar.DAY_OF_MONTH, +1); // is holiday, make it next day
}
}
}
calCp = new GregorianCalendar();
calCp.setTime(cal.getTime());
isSaturday = (calCp.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY);
isSunday = (calCp.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY);
isHoliday = holidays.contains(calCp);
} // end while
return calCp;
}
O(1) version that works and supports different weekend patterns and negative days:
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class DateUtil {
//Weekend patterns
public static final int WEEKEND_SAT_SUN = 0;
public static final int WEEKEND_FRI_SAT = 1;
public static final int WEEKEND_THU_FRI = 2;
public static final int WEEKEND_FRI_SUN = 3;
public static final int WEEKEND_FRI = 4;
public static final int WEEKEND_SAT = 5;
public static final int WEEKEND_SUN = 6;
//Weekend pattern by country
//#see https://en.wikipedia.org/wiki/Workweek_and_weekend
public static Map<String,Integer> weekendPatternByCountry = new HashMap<>();
static {
weekendPatternByCountry.put("CO",WEEKEND_SUN); //Colombia
weekendPatternByCountry.put("GQ",WEEKEND_SUN); //Equatorial Guinea
weekendPatternByCountry.put("IN",WEEKEND_SUN); //India
weekendPatternByCountry.put("MX",WEEKEND_SUN); //Mexico
weekendPatternByCountry.put("KP",WEEKEND_SUN); //North Korea
weekendPatternByCountry.put("UG",WEEKEND_SUN); //Uganda
weekendPatternByCountry.put("BN",WEEKEND_FRI_SUN); //Brunei Darussalam
weekendPatternByCountry.put("DJ",WEEKEND_FRI); //Djibouti
weekendPatternByCountry.put("IR",WEEKEND_FRI); //Iran
weekendPatternByCountry.put("AF",WEEKEND_THU_FRI); //Afghanistan
weekendPatternByCountry.put("NP",WEEKEND_SAT); //Nepal
weekendPatternByCountry.put("DZ",WEEKEND_FRI_SAT); //Algeria
weekendPatternByCountry.put("BH",WEEKEND_FRI_SAT); //Bahrain
weekendPatternByCountry.put("BD",WEEKEND_FRI_SAT); //Bangladesh
weekendPatternByCountry.put("EG",WEEKEND_FRI_SAT); //Egypt
weekendPatternByCountry.put("IQ",WEEKEND_FRI_SAT); //Iraq
weekendPatternByCountry.put("IL",WEEKEND_FRI_SAT); //Israel
weekendPatternByCountry.put("JO",WEEKEND_FRI_SAT); //Jordan
weekendPatternByCountry.put("KW",WEEKEND_FRI_SAT); //Kuwait
weekendPatternByCountry.put("LY",WEEKEND_FRI_SAT); //Libya
weekendPatternByCountry.put("MV",WEEKEND_FRI_SAT); //Maldives
weekendPatternByCountry.put("MR",WEEKEND_FRI_SAT); //Mauritania
weekendPatternByCountry.put("MY",WEEKEND_FRI_SAT); //Malaysia
weekendPatternByCountry.put("OM",WEEKEND_FRI_SAT); //Oman
weekendPatternByCountry.put("PS",WEEKEND_FRI_SAT); //Palestine
weekendPatternByCountry.put("QA",WEEKEND_FRI_SAT); //Qatar
weekendPatternByCountry.put("SA",WEEKEND_FRI_SAT); //Saudi Arabia
weekendPatternByCountry.put("SD",WEEKEND_FRI_SAT); //Sudan
weekendPatternByCountry.put("SY",WEEKEND_FRI_SAT); //Syria
weekendPatternByCountry.put("AE",WEEKEND_FRI_SAT); //United Arab Emirates
weekendPatternByCountry.put("YE",WEEKEND_FRI_SAT); //Yemen
}
//Adjustment vectors - precomputed adjustment
static int[][][] adjVector = new int[][][]{
{//WEEKEND_SAT_SUN
//Positive number of days
{1,0,-1,-2,-3,1,1},
{0,0},
{0,0,0,0,0,2,1},
//Negative number of days
{-1,3,2,1,0,-1,-1},
{0,0},
{-1,1,1,1,1,1,0}
},
{//WEEKEND_FRI_SAT
//Positive number of days
{0,-1,-2,-3,1,1,1},
{0,0},
{0,0,0,0,2,1,0},
//Negative number of days
{3,2,1,0,-1,-1,-1},
{0,0},
{1,1,1,1,1,0,-1}
},
{//WEEKEND_THU_FRI
//Positive number of days
{-1,-2,-3,1,1,1,0},
{0,0},
{0,0,0,2,1,0,0},
//Negative number of days
{2,1,0,-1,-1,-1,3},
{0,0},
{1,1,1,1,0,-1,1}
},
{//WEEKEND_FRI_SUN
//Positive number of days
{0,-1,-2,-3,-4,-4,0},
{1,0},
{0,0,0,0,0,-1,1},
//Negative number of days
{4,3,2,1,0,0,4},
{0,-1},
{1,1,1,1,1,0,2}
},
{//WEEKEND_FRI
//Positive number of days
{-1,-2,-3,-4,1,1,0},
{0},
{0,0,0,0,1,0,0},
//Negative number of days
{3,2,1,0,-1,-1,4},
{0},
{1,1,1,1,1,0,1}
},
{//WEEKEND_SAT
//Positive number of days
{0,-1,-2,-3,-4,1,1},
{0},
{0,0,0,0,0,1,0},
//Negative number of days
{4,3,2,1,0,-1,-1},
{0},
{1,1,1,1,1,1,0}
},
{//WEEKEND_SUN
//Positive number of days
{1,0,-1,-2,-3,-4,1},
{0},
{0,0,0,0,0,0,1},
//Negative number of days
{-1,4,3,2,1,0,-1},
{0},
{0,1,1,1,1,1,1}
}
};
//O(1) algorithm to add business days.
public static Date addBusinessDays(Date day, int days,int weekendPattern){
Calendar ret = Calendar.getInstance();
if(day != null) {
ret.setTime(day);
}
if(days != 0) {
int startDayofWeek = ret.get(Calendar.DAY_OF_WEEK)-1; //Zero based to use the vectors bellow.
int idx = days > 0 ? 0 : 3;
int howManyWeekendDays = 0;
int[][] adjV = adjVector[weekendPattern];
int numWeekendDaysInOneWeek = adjV[idx+1].length;
for(int i = 0; i < numWeekendDaysInOneWeek;i++){
int adjustmentA = adjV[idx][startDayofWeek]; //pattern shift
int adjustmentB = adjV[idx+1][i]; //day shift
howManyWeekendDays += (days-adjustmentA-adjustmentB)/(7-numWeekendDaysInOneWeek);
}
int adjustmentC = adjV[idx+2][startDayofWeek]; //f(0) adjustment
howManyWeekendDays += adjustmentC;
ret.add(Calendar.DATE,days + howManyWeekendDays);
//TODO: Extend to support holidays using recursion
// int numHolidays = getNumHolidaysInInterval(day,ret.getTime());
// if(numHolidays > 0) return addBusinessDays(ret.getTime,numHolidays);
}
return ret.getTime();
}
public static Date addBusinessDays(Date day, int days,String country){
Integer weekpat = weekendPatternByCountry.get(country);
return weekpat != null ? addBusinessDays(day,days,weekpat) : addBusinessDays(day,days,WEEKEND_SAT_SUN);
}
}
This is the method I came up with:
private Date addLaborDays(Integer days, Date date){
Collection<Date> holidaysList = getHolidays();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, 1);
Date dateTemp = cal.getTime();
if(days == 1) return dateTemp;
if(holidaysList.contains(dateTemp) || DateUtil.isWeekend(dateTemp)){
return addLaborDays(days, dateTemp);
} else {
return addLaborDays(days-1, dateTemp);
}
}
Method getHolidays() queries a custom holidays database table, and method DateUtil.isWeekend(dateTemp) returns true if dateTemp is Saturday or Sunday.
/* To Calculate 10 business days ahead of today's date
*/
public class DueDate {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
DueDate d = new DueDate();
String dueDate = d.getDueDate(10);
System.out.println("due Date " + dueDate);
}
public String getDueDate(int bday){
Calendar cal = new GregorianCalendar();
SimpleDateFormat fdate = new SimpleDateFormat("MM/dd/yyyy");
while(bday > 0){
cal.add(Calendar.DAY_OF_MONTH, 1);
if(noWeekendsorHolidays(cal)){
bday--;
}
}
return fdate.format(cal.getTime());
}
public boolean noWeekendsorHolidays(Calendar cal){
int day = cal.get(Calendar.DAY_OF_WEEK);
if(day == 1 || day == 7){
return false;
}
return true;
}
}
This one works for me, short and simple:
public static Date getBusinessDay(final Date date, final int businessDaysFromDate) {
final int max = 60;
if (date == null) {
return getBusinessDay(new Date(), businessDaysFromDate);
} else if (date != null && (businessDaysFromDate < 0 || businessDaysFromDate > max)) {
return getBusinessDay(date, 0);
} else {
final Calendar baseDateCal = Calendar.getInstance();
baseDateCal.setTime(date);
for (int i = 1; i <= businessDaysFromDate; i++) {
baseDateCal.add(Calendar.DATE, 1);
while (baseDateCal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || baseDateCal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
baseDateCal.add(Calendar.DATE, 1);
}
}
return baseDateCal.getTime();
}
}
Adding two business days to current date:
Date today = new Date();
Calendar cal1 = Calendar.getInstance();
cal1.setTime(today);
switch(cal1.get(Calendar.DAY_OF_WEEK)){
case 1:
cal1.add(Calendar.DATE, 2);
break;
case 2:
cal1.add(Calendar.DATE, 2);
break;
case 3:
cal1.add(Calendar.DATE, 2);
break;
case 4:
cal1.add(Calendar.DATE, 2);
break;
case 5:
cal1.add(Calendar.DATE, 4);
break;
case 6:
cal1.add(Calendar.DATE, 4);
break;
case 7:
cal1.add(Calendar.DATE, 3);
break;
}
// You may also set the time to meet your purpose:
cal1.set(Calendar.HOUR_OF_DAY, 23);
cal1.set(Calendar.MINUTE, 59);
cal1.set(Calendar.SECOND, 59);
cal1.set(Calendar.MILLISECOND, 00);
Date twoWeekdaysAhead = cal1.getTime();
Most of the answer I've found online didn't work as expected, so I tweaked an example on this thread, How to get current date and add five working days in Java. The code below appears to work better.
public static Date addWorkingDays(Date date, int days) {
if (days > 0) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int daysAdded = 0;
do {
cal.add(Calendar.DATE, 1);
if (isWorkingDay(cal)) {
daysAdded++;
}
} while (daysAdded < days);
return cal.getTime();;
} else {
return date;
}
}
private static boolean isWorkingDay(Calendar cal) {
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == Calendar.SUNDAY || dayOfWeek == Calendar.SATURDAY)
return false;
// tests for other holidays here
return true;
}

How do I calculate someone's age in Java?

I want to return an age in years as an int in a Java method.
What I have now is the following where getBirthDate() returns a Date object (with the birth date ;-)):
public int getAge() {
long ageInMillis = new Date().getTime() - getBirthDate().getTime();
Date age = new Date(ageInMillis);
return age.getYear();
}
But since getYear() is deprecated I'm wondering if there is a better way to do this? I'm not even sure this works correctly, since I have no unit tests in place (yet).
JDK 8 makes this easy and elegant:
public class AgeCalculator {
public static int calculateAge(LocalDate birthDate, LocalDate currentDate) {
if ((birthDate != null) && (currentDate != null)) {
return Period.between(birthDate, currentDate).getYears();
} else {
return 0;
}
}
}
A JUnit test to demonstrate its use:
public class AgeCalculatorTest {
#Test
public void testCalculateAge_Success() {
// setup
LocalDate birthDate = LocalDate.of(1961, 5, 17);
// exercise
int actual = AgeCalculator.calculateAge(birthDate, LocalDate.of(2016, 7, 12));
// assert
Assert.assertEquals(55, actual);
}
}
Everyone should be using JDK 8 by now. All earlier versions have passed the end of their support lives.
Check out Joda, which simplifies date/time calculations (Joda is also the basis of the new standard Java date/time apis, so you'll be learning a soon-to-be-standard API).
e.g.
LocalDate birthdate = new LocalDate (1970, 1, 20);
LocalDate now = new LocalDate();
Years age = Years.yearsBetween(birthdate, now);
which is as simple as you could want. The pre-Java 8 stuff is (as you've identified) somewhat unintuitive.
EDIT: Java 8 has something very similar and is worth checking out.
EDIT: This answer pre-dates the Java 8 date/time classes and is not current any more.
Modern answer and overview
a) Java-8 (java.time-package)
LocalDate start = LocalDate.of(1996, 2, 29);
LocalDate end = LocalDate.of(2014, 2, 28); // use for age-calculation: LocalDate.now()
long years = ChronoUnit.YEARS.between(start, end);
System.out.println(years); // 17
Note that the expression LocalDate.now() is implicitly related to the system timezone (which is often overlooked by users). For clarity it is generally better to use the overloaded method now(ZoneId.of("Europe/Paris")) specifying an explicit timezone (here "Europe/Paris" as example). If the system timezone is requested then my personal preference is to write LocalDate.now(ZoneId.systemDefault()) to make the relation to the system timezone clearer. This is more writing effort but makes reading easier.
b) Joda-Time
Please note that the proposed and accepted Joda-Time-solution yields a different computation result for the dates shown above (a rare case), namely:
LocalDate birthdate = new LocalDate(1996, 2, 29);
LocalDate now = new LocalDate(2014, 2, 28); // test, in real world without args
Years age = Years.yearsBetween(birthdate, now);
System.out.println(age.getYears()); // 18
I consider this as a small bug but the Joda-team has a different view on this weird behaviour and does not want to fix it (weird because the day-of-month of end date is smaller than of start date so the year should be one less). See also this closed issue.
c) java.util.Calendar etc.
For comparison see the various other answers. I would not recommend using these outdated classes at all because the resulting code is still errorprone in some exotic cases and/or way too complex considering the fact that the original question sounds so simple. In year 2015 we have really better libraries.
d) About Date4J:
The proposed solution is simple but will sometimes fail in case of leap years. Just evaluating the day of year is not reliable.
e) My own library Time4J:
This works similar to Java-8-solution. Just replace LocalDate by PlainDate and ChronoUnit.YEARS by CalendarUnit.YEARS. However, getting "today" requires an explicit timezone reference.
PlainDate start = PlainDate.of(1996, 2, 29);
PlainDate end = PlainDate.of(2014, 2, 28);
// use for age-calculation (today):
// => end = SystemClock.inZonalView(EUROPE.PARIS).today();
// or in system timezone: end = SystemClock.inLocalView().today();
long years = CalendarUnit.YEARS.between(start, end);
System.out.println(years); // 17
Calendar now = Calendar.getInstance();
Calendar dob = Calendar.getInstance();
dob.setTime(...);
if (dob.after(now)) {
throw new IllegalArgumentException("Can't be born in the future");
}
int year1 = now.get(Calendar.YEAR);
int year2 = dob.get(Calendar.YEAR);
int age = year1 - year2;
int month1 = now.get(Calendar.MONTH);
int month2 = dob.get(Calendar.MONTH);
if (month2 > month1) {
age--;
} else if (month1 == month2) {
int day1 = now.get(Calendar.DAY_OF_MONTH);
int day2 = dob.get(Calendar.DAY_OF_MONTH);
if (day2 > day1) {
age--;
}
}
// age is now correct
/**
* This Method is unit tested properly for very different cases ,
* taking care of Leap Year days difference in a year,
* and date cases month and Year boundary cases (12/31/1980, 01/01/1980 etc)
**/
public static int getAge(Date dateOfBirth) {
Calendar today = Calendar.getInstance();
Calendar birthDate = Calendar.getInstance();
int age = 0;
birthDate.setTime(dateOfBirth);
if (birthDate.after(today)) {
throw new IllegalArgumentException("Can't be born in the future");
}
age = today.get(Calendar.YEAR) - birthDate.get(Calendar.YEAR);
// If birth date is greater than todays date (after 2 days adjustment of leap year) then decrement age one year
if ( (birthDate.get(Calendar.DAY_OF_YEAR) - today.get(Calendar.DAY_OF_YEAR) > 3) ||
(birthDate.get(Calendar.MONTH) > today.get(Calendar.MONTH ))){
age--;
// If birth date and todays date are of same month and birth day of month is greater than todays day of month then decrement age
}else if ((birthDate.get(Calendar.MONTH) == today.get(Calendar.MONTH )) &&
(birthDate.get(Calendar.DAY_OF_MONTH) > today.get(Calendar.DAY_OF_MONTH ))){
age--;
}
return age;
}
I simply use the milliseconds in a year constant value to my advantage:
Date now = new Date();
long timeBetween = now.getTime() - age.getTime();
double yearsBetween = timeBetween / 3.15576e+10;
int age = (int) Math.floor(yearsBetween);
If you are using GWT you will be limited to using java.util.Date, here is a method that takes the date as integers, but still uses java.util.Date:
public int getAge(int year, int month, int day) {
Date now = new Date();
int nowMonth = now.getMonth()+1;
int nowYear = now.getYear()+1900;
int result = nowYear - year;
if (month > nowMonth) {
result--;
}
else if (month == nowMonth) {
int nowDay = now.getDate();
if (day > nowDay) {
result--;
}
}
return result;
}
It's perhaps surprising to note that you don't need to know how many days or months there are in a year or how many days are in those months, likewise, you don't need to know about leap years, leap seconds, or any of that stuff using this simple, 100% accurate method:
public static int age(Date birthday, Date date) {
DateFormat formatter = new SimpleDateFormat("yyyyMMdd");
int d1 = Integer.parseInt(formatter.format(birthday));
int d2 = Integer.parseInt(formatter.format(date));
int age = (d2-d1)/10000;
return age;
}
With the date4j library :
int age = today.getYear() - birthdate.getYear();
if(today.getDayOfYear() < birthdate.getDayOfYear()){
age = age - 1;
}
This is an improved version of the one above... considering that you want age to be an 'int'. because sometimes you don't want to fill your program with a bunch of libraries.
public int getAge(Date dateOfBirth) {
int age = 0;
Calendar born = Calendar.getInstance();
Calendar now = Calendar.getInstance();
if(dateOfBirth!= null) {
now.setTime(new Date());
born.setTime(dateOfBirth);
if(born.after(now)) {
throw new IllegalArgumentException("Can't be born in the future");
}
age = now.get(Calendar.YEAR) - born.get(Calendar.YEAR);
if(now.get(Calendar.DAY_OF_YEAR) < born.get(Calendar.DAY_OF_YEAR)) {
age-=1;
}
}
return age;
}
The correct answer using JodaTime is:
public int getAge() {
Years years = Years.yearsBetween(new LocalDate(getBirthDate()), new LocalDate());
return years.getYears();
}
You could even shorten it into one line if you like. I copied the idea from BrianAgnew's answer, but I believe this is more correct as you see from the comments there (and it answers the question exactly).
Try to copy this one in your code, then use the method to get the age.
public static int getAge(Date birthday)
{
GregorianCalendar today = new GregorianCalendar();
GregorianCalendar bday = new GregorianCalendar();
GregorianCalendar bdayThisYear = new GregorianCalendar();
bday.setTime(birthday);
bdayThisYear.setTime(birthday);
bdayThisYear.set(Calendar.YEAR, today.get(Calendar.YEAR));
int age = today.get(Calendar.YEAR) - bday.get(Calendar.YEAR);
if(today.getTimeInMillis() < bdayThisYear.getTimeInMillis())
age--;
return age;
}
I use this piece of code for age calculation ,Hope this helps ..no libraries used
private static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
public static int calculateAge(String date) {
int age = 0;
try {
Date date1 = dateFormat.parse(date);
Calendar now = Calendar.getInstance();
Calendar dob = Calendar.getInstance();
dob.setTime(date1);
if (dob.after(now)) {
throw new IllegalArgumentException("Can't be born in the future");
}
int year1 = now.get(Calendar.YEAR);
int year2 = dob.get(Calendar.YEAR);
age = year1 - year2;
int month1 = now.get(Calendar.MONTH);
int month2 = dob.get(Calendar.MONTH);
if (month2 > month1) {
age--;
} else if (month1 == month2) {
int day1 = now.get(Calendar.DAY_OF_MONTH);
int day2 = dob.get(Calendar.DAY_OF_MONTH);
if (day2 > day1) {
age--;
}
}
} catch (ParseException e) {
e.printStackTrace();
}
return age ;
}
The fields birth and effect are both date fields:
Calendar bir = Calendar.getInstance();
bir.setTime(birth);
int birthNm = bir.get(Calendar.DAY_OF_YEAR);
int birthYear = bir.get(Calendar.YEAR);
Calendar eff = Calendar.getInstance();
eff.setTime(effect);
This basically a modification of John O's solution without using depreciated methods. I spent a fair amount of time trying to get his code to work in in my code. Maybe this will save others that time.
What about this one?
public Integer calculateAge(Date date) {
if (date == null) {
return null;
}
Calendar cal1 = Calendar.getInstance();
cal1.setTime(date);
Calendar cal2 = Calendar.getInstance();
int i = 0;
while (cal1.before(cal2)) {
cal1.add(Calendar.YEAR, 1);
i += 1;
}
return i;
}
String dateofbirth has the date of birth. and format is whatever (defined in the following line):
org.joda.time.format.DateTimeFormatter formatter = org.joda.time.format.DateTimeFormat.forPattern("mm/dd/yyyy");
Here is how to format:
org.joda.time.DateTime birthdateDate = formatter.parseDateTime(dateofbirth );
org.joda.time.DateMidnight birthdate = new org.joda.time.DateMidnight(birthdateDate.getYear(), birthdateDate.getMonthOfYear(), birthdateDate.getDayOfMonth() );
org.joda.time.DateTime now = new org.joda.time.DateTime();
org.joda.time.Years age = org.joda.time.Years.yearsBetween(birthdate, now);
java.lang.String ageStr = java.lang.String.valueOf (age.getYears());
Variable ageStr will have the years.
Elegant, seemingly correct, timestamp difference based variant of Yaron Ronen solution.
I am including a unit test to prove when and why it is not correct. It is impossible due (to possibly) different number of leap days (and seconds) in any timestamp difference. The discrepancy should be max +-1 day (and one second) for this algorithm, see test2(), whereas Yaron Ronen solution based on completely constant assumption of timeDiff / MILLI_SECONDS_YEAR can differ 10 days for a 40ty year old, nevertheless this variant is incorrect too.
It is tricky, because this improved variant, using formula diffAsCalendar.get(Calendar.YEAR) - 1970, returns correct results most of the time, as number of leap years in on average same between two dates.
/**
* Compute person's age based on timestamp difference between birth date and given date
* and prove it is INCORRECT approach.
*/
public class AgeUsingTimestamps {
public int getAge(Date today, Date dateOfBirth) {
long diffAsLong = today.getTime() - dateOfBirth.getTime();
Calendar diffAsCalendar = Calendar.getInstance();
diffAsCalendar.setTimeInMillis(diffAsLong);
return diffAsCalendar.get(Calendar.YEAR) - 1970; // base time where timestamp=0, precisely 1/1/1970 00:00:00
}
final static DateFormat df = new SimpleDateFormat("dd.MM.yyy HH:mm:ss");
#Test
public void test1() throws Exception {
Date dateOfBirth = df.parse("10.1.2000 00:00:00");
assertEquals(87, getAge(df.parse("08.1.2088 23:59:59"), dateOfBirth));
assertEquals(87, getAge(df.parse("09.1.2088 23:59:59"), dateOfBirth));
assertEquals(88, getAge(df.parse("10.1.2088 00:00:01"), dateOfBirth));
}
#Test
public void test2() throws Exception {
// between 2000 and 2021 was 6 leap days
// but between 1970 (base time) and 1991 there was only 5 leap days
// therefore age is switched one day earlier
// See http://www.onlineconversion.com/leapyear.htm
Date dateOfBirth = df.parse("10.1.2000 00:00:00");
assertEquals(20, getAge(df.parse("08.1.2021 23:59:59"), dateOfBirth));
assertEquals(20, getAge(df.parse("09.1.2021 23:59:59"), dateOfBirth)); // ERROR! returns incorrect age=21 here
assertEquals(21, getAge(df.parse("10.1.2021 00:00:01"), dateOfBirth));
}
}
public class CalculateAge {
private int age;
private void setAge(int age){
this.age=age;
}
public void calculateAge(Date date){
Calendar calendar=Calendar.getInstance();
Calendar calendarnow=Calendar.getInstance();
calendarnow.getTimeZone();
calendar.setTime(date);
int getmonth= calendar.get(calendar.MONTH);
int getyears= calendar.get(calendar.YEAR);
int currentmonth= calendarnow.get(calendarnow.MONTH);
int currentyear= calendarnow.get(calendarnow.YEAR);
int age = ((currentyear*12+currentmonth)-(getyears*12+getmonth))/12;
setAge(age);
}
public int getAge(){
return this.age;
}
/**
* Compute from string date in the format of yyyy-MM-dd HH:mm:ss the age of a person.
* #author Yaron Ronen
* #date 04/06/2012
*/
private int computeAge(String sDate)
{
// Initial variables.
Date dbDate = null;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// Parse sDate.
try
{
dbDate = (Date)dateFormat.parse(sDate);
}
catch(ParseException e)
{
Log.e("MyApplication","Can not compute age from date:"+sDate,e);
return ILLEGAL_DATE; // Const = -2
}
// Compute age.
long timeDiff = System.currentTimeMillis() - dbDate.getTime();
int age = (int)(timeDiff / MILLI_SECONDS_YEAR); // MILLI_SECONDS_YEAR = 31558464000L;
return age;
}
Here is the java code to calculate age in year, month and days.
public static AgeModel calculateAge(long birthDate) {
int years = 0;
int months = 0;
int days = 0;
if (birthDate != 0) {
//create calendar object for birth day
Calendar birthDay = Calendar.getInstance();
birthDay.setTimeInMillis(birthDate);
//create calendar object for current day
Calendar now = Calendar.getInstance();
Calendar current = Calendar.getInstance();
//Get difference between years
years = now.get(Calendar.YEAR) - birthDay.get(Calendar.YEAR);
//get months
int currMonth = now.get(Calendar.MONTH) + 1;
int birthMonth = birthDay.get(Calendar.MONTH) + 1;
//Get difference between months
months = currMonth - birthMonth;
//if month difference is in negative then reduce years by one and calculate the number of months.
if (months < 0) {
years--;
months = 12 - birthMonth + currMonth;
} else if (months == 0 && now.get(Calendar.DATE) < birthDay.get(Calendar.DATE)) {
years--;
months = 11;
}
//Calculate the days
if (now.get(Calendar.DATE) > birthDay.get(Calendar.DATE))
days = now.get(Calendar.DATE) - birthDay.get(Calendar.DATE);
else if (now.get(Calendar.DATE) < birthDay.get(Calendar.DATE)) {
int today = now.get(Calendar.DAY_OF_MONTH);
now.add(Calendar.MONTH, -1);
days = now.getActualMaximum(Calendar.DAY_OF_MONTH) - birthDay.get(Calendar.DAY_OF_MONTH) + today;
} else {
days = 0;
if (months == 12) {
years++;
months = 0;
}
}
}
//Create new Age object
return new AgeModel(days, months, years);
}
Easiest way without any libraries:
long today = new Date().getTime();
long diff = today - birth;
long age = diff / DateUtils.YEAR_IN_MILLIS;
With Java 8, we can calculate a person age with one line of code:
public int calCAge(int year, int month,int days){
return LocalDate.now().minus(Period.of(year, month, days)).getYear();
}
Simple solution in kotlin.
fun getAgeOfUser(date: String?) : Int {
if(date.isNullOrEmpty()) return 0
val calendar = Calendar.getInstance()
val cYear = calendar.get(Calendar.YEAR)
val cDay = calendar.get(Calendar.DAY_OF_YEAR)
val dob = Calendar.getInstance()
dob.timeInMillis = date.toLong()
val bYear = dob.get(Calendar.YEAR)
val bDay = dob.get(Calendar.DAY_OF_YEAR)
var age = cYear - bYear
if(cDay < bDay) age--
return age
}
public int getAge(Date dateOfBirth)
{
Calendar now = Calendar.getInstance();
Calendar dob = Calendar.getInstance();
dob.setTime(dateOfBirth);
if (dob.after(now))
{
throw new IllegalArgumentException("Can't be born in the future");
}
int age = now.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
if (now.get(Calendar.DAY_OF_YEAR) < dob.get(Calendar.DAY_OF_YEAR))
{
age--;
}
return age;
}
import java.io.*;
class AgeCalculator
{
public static void main(String args[])
{
InputStreamReader ins=new InputStreamReader(System.in);
BufferedReader hey=new BufferedReader(ins);
try
{
System.out.println("Please enter your name: ");
String name=hey.readLine();
System.out.println("Please enter your birth date: ");
String date=hey.readLine();
System.out.println("please enter your birth month:");
String month=hey.readLine();
System.out.println("please enter your birth year:");
String year=hey.readLine();
System.out.println("please enter current year:");
String cYear=hey.readLine();
int bDate = Integer.parseInt(date);
int bMonth = Integer.parseInt(month);
int bYear = Integer.parseInt(year);
int ccYear=Integer.parseInt(cYear);
int age;
age = ccYear-bYear;
int totalMonth=12;
int yourMonth=totalMonth-bMonth;
System.out.println(" Hi " + name + " your are " + age + " years " + yourMonth + " months old ");
}
catch(IOException err)
{
System.out.println("");
}
}
}
public int getAge(String birthdate, String today){
// birthdate = "1986-02-22"
// today = "2014-09-16"
// String class has a split method for splitting a string
// split(<delimiter>)
// birth[0] = 1986 as string
// birth[1] = 02 as string
// birth[2] = 22 as string
// now[0] = 2014 as string
// now[1] = 09 as string
// now[2] = 16 as string
// **birth** and **now** arrays are automatically contains 3 elements
// split method here returns 3 elements because of yyyy-MM-dd value
String birth[] = birthdate.split("-");
String now[] = today.split("-");
int age = 0;
// let us convert string values into integer values
// with the use of Integer.parseInt(<string>)
int ybirth = Integer.parseInt(birth[0]);
int mbirth = Integer.parseInt(birth[1]);
int dbirth = Integer.parseInt(birth[2]);
int ynow = Integer.parseInt(now[0]);
int mnow = Integer.parseInt(now[1]);
int dnow = Integer.parseInt(now[2]);
if(ybirth < ynow){ // has age if birth year is lesser than current year
age = ynow - ybirth; // let us get the interval of birth year and current year
if(mbirth == mnow){ // when birth month comes, it's ok to have age = ynow - ybirth if
if(dbirth > dnow) // birth day is coming. need to subtract 1 from age. not yet a bday
age--;
}else if(mbirth > mnow){ age--; } // birth month is comming. need to subtract 1 from age
}
return age;
}
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.Period;
public class AgeCalculator1 {
public static void main(String args[]) {
LocalDate start = LocalDate.of(1970, 2, 23);
LocalDate end = LocalDate.now(ZoneId.systemDefault());
Period p = Period.between(start, end);
//The output of the program is :
//45 years 6 months and 6 days.
System.out.print(p.getYears() + " year" + (p.getYears() > 1 ? "s " : " ") );
System.out.print(p.getMonths() + " month" + (p.getMonths() > 1 ? "s and " : " and ") );
System.out.print(p.getDays() + " day" + (p.getDays() > 1 ? "s.\n" : ".\n") );
}//method main ends here.
}
I appreciate all correct answers but this is the kotlin answer for the same question
I hope would be helpful to kotlin developers
fun calculateAge(birthDate: Date): Int {
val now = Date()
val timeBetween = now.getTime() - birthDate.getTime();
val yearsBetween = timeBetween / 3.15576e+10;
return Math.floor(yearsBetween).toInt()
}

Categories

Resources