首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >datepicker在DatePicker中指明出生日期,然后显示下一个生日和生日的天数?

datepicker在DatePicker中指明出生日期,然后显示下一个生日和生日的天数?
EN

Stack Overflow用户
提问于 2020-04-26 18:49:14
回答 2查看 71关注 0票数 0

我的问题是,在选择了Datepiker之后,如何计算出我的年龄,我已经有了下一个生日的剩余天数,现在我想要计算一下我的下一个生日。以下是我的代码

代码语言:javascript
复制
 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天。

what i pretend to obtain

EN

回答 2

Stack Overflow用户

发布于 2020-04-27 21:53:26

在我的上一个应用程序中,我将日期转换为毫秒,这是一个很长的值,我从今天的毫秒日期中减去生日也是毫秒。

票数 0
EN

Stack Overflow用户

发布于 2020-04-30 18:13:56

我找到了答案,就是加上这个:

代码语言:javascript
复制
cal1.set(ano,mes,dia);
aniv.setText((((cal2.getTimeInMillis() - cal1.getTimeInMillis())
/ (24 * 60 * 60 * 1000) / 365) +1) + "º");
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61439442

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档