我的问题是,在选择了Datepiker之后,如何计算出我的年龄,我已经有了下一个生日的剩余天数,现在我想要计算一下我的下一个生日。以下是我的代码
TextView aniv =(TextView) findViewById(R.id.txtaniv);
TextView dias =(TextView) findViewById(R.id.diasfaltam);
// Resource Recovery
SharedPreferences dados=getSharedPreferences("info",0);
int dia = dados.getInt("dia",0);
//para mes ficar com a nomeração "normal"
int mes = dados.getInt("mes",0)+1;
int ano = dados.getInt("ano",0);
aniv.setText(dia + "/" + mes + "/" +ano);
// Perform account to determine how many days are left until the birthday
// Create two instances in the calendar
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
// Let's get the current system date
int anoatual =cal2.get(Calendar.YEAR);
int mesatual =cal2.get(Calendar.MONTH);
int diaatual =cal2.get(Calendar.DAY_OF_MONTH);
// need to check if the birthday has already occurred or not this year
if(mesatual>mes-1) {
anoatual=anoatual+1;
}
if(mesatual==mes-1&&diaatual>dia){
anoatual=anoatual+1;
}
// set the next anniversary date, based on the retrieved data
cal1.set(anoatual, mes-1, dia);
// You need to represent the date in milliseconds to be able to make the difference between them
long milis1 = cal1.getTimeInMillis();
long milis2 = cal2.getTimeInMillis();
// Calculate the difference between the dates
long diff = milis1 - milis2;
// convert the difference in milliseconds to days
long diffDays = diff / (24 * 60 * 60 * 1000);
// Test the displayed result, to check that there are no errors in the calculations
Toast toast = Toast.makeText(getApplicationContext(),"number of days until anniversary
" +diffDays,Toast.LENGTH_LONG);
toast.show();
dias.setText(""+diffDays);
}这是我从你1990年12月7日生日当天得到的200天。我也不想在你37岁生日时再给你200天。
发布于 2020-04-27 21:53:26
在我的上一个应用程序中,我将日期转换为毫秒,这是一个很长的值,我从今天的毫秒日期中减去生日也是毫秒。
发布于 2020-04-30 18:13:56
我找到了答案,就是加上这个:
cal1.set(ano,mes,dia);
aniv.setText((((cal2.getTimeInMillis() - cal1.getTimeInMillis())
/ (24 * 60 * 60 * 1000) / 365) +1) + "º");https://stackoverflow.com/questions/61439442
复制相似问题