2011-03-04 5 views
0

가능한 중복은 : 사망 당시의 나이를 어떻게 계산합니까?

SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); if(petDetails.getDateOfDeath() != null){ String formatedDateOfDeath = formatter.format(petDetails.getDateOfDeath()); String formateDateOfBirth = formatter.format(petDetails.getDateOfBirth()); } 


How can I calculate the age of a person in year, month, days?
How can I calculate the difference between two dates

는 어떻게 위에서 죽음의 나이를 계산할 수 있습니다. 나는 어떤 externallibraries를 사용하고 싶지 않다.

EDIT : 내가 지금까지 가지고있는 것을 보아라. 다른 스레드들 중 아무 것도 나의 것과 같다. 대부분은 DOB에서 오늘에 이르기까지이며, 사용하는 형식이 아닙니다.

+0

가능한 중복 [년, 월, 일의 나이를 어떻게 계산할 수 있습니까?] (http://stackoverflow.com/questions/453208/how-can-i-calculate-the-age-of - 사람 - 년 - 월 - 일). [이 답변] (http://stackoverflow.com/questions/9/how-do-i-calculate-someones-age-in-c/11942#11942)도 참조하십시오. –

+0

또는 http://stackoverflow.com/questions/1116123/how-do-i-calculate-someones-age-in-java –

+4

한 시간 전 그의 질문과 중복 될 수 있습니다. http://stackoverflow.com/questions/5194216/how-can-i-calculate-the-difference-between-two-dates-closed – Riggy

답변

0

이 시도 :

public class Age { 

public static void main(String[] args) { 
     Calendar birthDate = new GregorianCalendar(1979, 1, 1); 
     Calendar deathDate = new GregorianCalendar(2011, 1, 1); 
     int age = deathDate.get(Calendar.YEAR) - birthDate.get(Calendar.YEAR); 
     if ((birthDate.get(Calendar.MONTH) > deathDate.get(Calendar.MONTH)) 
      || (birthDate.get(Calendar.MONTH) == deathDate.get(Calendar.MONTH) && birthDate.get(Calendar.DAY_OF_MONTH) > deathDate 
       .get(Calendar.DAY_OF_MONTH))) { 
      age--; 
     } 
     System.out.println(age); 
     } 

}

+0

그것과 같은 것이 아닙니다. 칼런 더 필드 ddude에 넣으려는 것이 무엇입니까! – code511788465541441

+0

getDateOfBirth는 무엇을 반환합니까? 날짜 객체입니까? – Mike

+0

@ 예. 그렇습니다. 날짜입니다. – code511788465541441

0

당신은 문자열로 변환하지 않고이 문제를 해결 할 수 있습니다. . getDateOfBirth 및 getDateOfDeath 반환 날짜 객체 이후 , 당신은 Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.

이 일을하는 아주 간단한 방법은
긴 millisecondsDiff = petDetails.getDateOfDeath() getTime를 할 수있는 그들에 .getTime() 메소드를 사용할 수 있습니다 - petDetails을 .getDateOfBirth(). getTime;

그러면이 길이에서 직접 새 날짜 개체를 만들거나 적절한 계산을 수행하여 밀리 초를 일로 변경할 수 있습니다. 즉
긴 기간 = 밀리 초 Diff/(1000 * 60 * 60 * 24);

+0

매년 정확하게 똑같은 양의 초와 일이있는 경우에만 제대로 작동합니다. 우리가 알고있는 사실은 그렇지 않고 내가 생각하는 가장자리로 이어질 수 있습니다. – Voo

+0

이 http://www.java2s.com/Code/Java/Development-Class/Computedaysbetweenbetween2dates.htm 일별로 나누기 전에 차이에 1 시간을 추가하는 것처럼 보입니다. 모퉁이 사건을 해결하는 데 도움이 될까요? – Mike

관련 문제