2014-09-02 62 views
0

我在Xamarin中創建了一個DatePicker,並且我有一個問題。我試圖通過增加出生年份,月份和日期來計算一個人的年齡。但是,調試後的代碼在我將年數轉換爲字符串的時候停止了,給了我一個錯誤:「引發了Android.Content.Res.Resources + NotFoundException。字符串資源ID#0x2」DateTimes年差

Xamarin代碼:

 base.OnCreate (bundle); 

     SetContentView (Resource.Layout.AddDataLayout); 

     Button regbutton = FindViewById<Button> (Resource.Id.regButton); 
     DatePicker date = FindViewById<DatePicker> (Resource.Id.datePicker); 

     //regbutton.Enabled = false; 



     regbutton.Click += delegate 
     { 
      DateTime zeroTime = new DateTime(1, 1, 1); 
      DateTime BornDate = date.DateTime; 
      DateTime sToday = DateTime.Today; 
      TimeSpan span = sToday - BornDate; 
      int years = (zeroTime + span).Year - 1; 
      string a = Convert.ToString(years); 
      Toast.MakeText(this,a , ToastLength.Long).Show(); 
      this.Finish(); 
     }; 
+0

會拋出異常,如果你只是做years.ToString()?順便說一句,如何根據出生日期計算年齡檢查正確實施 - http://stackoverflow.com/questions/9/how-do-i-calculate-someones-age-in-c – 2014-09-02 06:32:10

+2

鑑於例外,我認爲這個問題有錯誤的標題。 – Dirk 2014-09-02 06:38:18

+0

我使用了Ivan提到的另一種方法,現在我在OnCreate方法結尾處將問題解析爲「字符串資源ID#0x14」。我還在Visual Studio中以Consol App的身份編寫代碼。它工作得很好。 – gepont 2014-09-02 07:17:24

回答

-2
Calendar firstCalendar = Calendar.getInstance();   

Calendar secondCalendar = Calendar.getInstance(); 

long diff = currentCalendar.getTimeInMillis() - calendar.getTimeInMillis(); 
int sec = (int) (diff/1000); 
int min = sec/60; 
int hr = (int) (min/60); 
int days = hr/24; 
int month = days/30; 
int years = month/12 



if(sec>60){ 
     if(min>60){ 
      if(hr>24){ 
       if(days>30){ 
        if(month>12){ 
         submitDiffrence = Integer.toString(month)+" Years ago"; 
        }else{ 
         submitDiffrence = Integer.toString(month)+" month ago"; 
        } 
       }else{ 
        submitDiffrence = Integer.toString(days)+" days ago"; 
       } 
      }else{ 
       submitDiffrence = Integer.toString(hr)+" hour ago"; 
      } 
     }else{ 
      submitDiffrence = Long.toString(min)+" min ago"; 
     } 
    }else{ 
     submitDiffrence = Long.toString(sec)+" sec ago"; 
    } 
+0

如何解決OP問題? :/ – Reniuz 2014-09-02 06:47:58