2012-10-05 5 views
5

Ich mache eine App, die verwandt ist, um das Alter einer Person nach der gegebenen Eingabe des Geburtstagsdatums zu erhalten. Dafür erhalte ich vom folgenden Code die Gesamtzahl der Tage von diesem Datum bis zum aktuellen Datum.Android Wie man die Gesamtzahl der Tage in Jahre, Monate und Tage genau ändert?

 String strThatDay = "1991/05/10"; 
     SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd"); 
     Date d = null; 
     try { 

     try { 
     d = formatter.parse(strThatDay); 
     Log.i(TAG, "" +d); 
     } catch (java.text.ParseException e) { 

     e.printStackTrace(); 
     } 
     } catch (ParseException e) { 

     e.printStackTrace(); 
     } 
     Calendar thatDay = Calendar.getInstance(); 
     thatDay.setTime(d); //rest is the same.... 

     Calendar today = Calendar.getInstance(); 
     long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); 
     long days = diff/(24 * 60 * 60 * 1000); 

von diesem Code bekomme ich die Gesamtzahl der Tage. so meine Anforderung ist die Gesamtzahl der Tage in bis Jahre, Monate und Tage genau konvertieren .. bitte helfen ....

+0

Es gibt mathematische Operatoren namens% und /, die für Modul und Division verwendet werden. 12 Monate im Jahr, 30 Tage im Monat, 356 Tage im Jahr. Das sollte genug sein. –

+0

@VinaySShenoy wie man das ein einfaches Beispiel ... – NagarjunaReddy

+0

@VinaySShenoy für einige Jahre haben wir 355 Tage und für Monate 31,30,29 und 28 Tage. Wie können wir dieses Problem lösen –

Antwort

6

Sie sollten die Duration Klasse verwenden:

Duration duration = new Duration(); 
duration.add(today); 
duration.substract(birthDate); 
int years = duration.getYears(); 
int months = duration.getMonths(); 
int days = duration.getDays(); 

Einige andere Alternativen umfassen die Verwendung eines Zeitmanagement Bibliothek: Joda Zeit. Siehe Calculate age in Years, Months, Days, Hours, Minutes, and Seconds

3
String strThatDay = "1991/05/10"; 
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd"); 
    Date thatDate = null; 
    try { 

    try { 
    thatDate = formatter.parse(strThatDay); 

    Calendar thatDay = Calendar.getInstance(); 
    thatDay.setTime(thatDate); 
    Calendar toDay = Calendar.getInstance(); 
    toDay.setTime(thatDate); 

    toDay.add(Calendar.DATE, noOfDays); 

    int year = toDay.getTime().getYear() - thatDay.getTime().getYear(); 
    int month = toDay.getTime().getMonth() - thatDay.getTime().getMonth(); 
    if(month<0){ 
     year-- 
     month = month+12; 
    } 
    int days = toDay.getTime().getDate() - thatDay.getTime().getDate(); 
    if(month<0){ 
     month-- 
     days = days+ toDay.getMaximum(Calendar.MONTH);; 
    } 
Verwandte Themen