当我试着计算生日的日子 总是给我错误的天数
你能帮我解决什么问题吗?
Calendar call1 = Calendar.getInstance();
Calendar call2 = Calendar.getInstance();
int day2 = call2.get(Calendar.DAY_OF_MONTH);
int month2 = call2.get(Calendar.MONTH );
int year2 = call2.get(Calendar.YEAR);
if (month2 > month ) {
}
else if (month == month2 ){
if(year2 < day ){
}
}call1.set(day2, month , day);
long millis = call2.getTimeInMillis()
- call1.getTimeInMillis();
long days = millis / 86400000L;
Toast.makeText(this.getApplicationContext(), "The number of days until your birthday"
+ days, Toast.LENGTH_SHORT ).show();
text2.setText(""+ days);
text2.setTextColor(Color.parseColor("#990000"));
这是代码的第一部分:
SharedPreferences dp2 = this.getSharedPreferences("dp", 0);
int day = dp2.getInt("day", 0);
int month = dp2.getInt("month", 0) + 1;
int year = dp2.getInt("year", 0);
text1.setText(day + "/" + month + "/" + year);
答案 0 :(得分:2)
使用以下方法查找两个日期之间的差异。
/**
* Get a diff between two dates
* @param date1 the oldest date
* @param date2 the newest date
* @param timeUnit the unit in which you want the diff
* @return the diff value, in the provided unit
*/
public static long getDateDiff(Date date1, Date date2, TimeUnit timeUnit) {
long diffInMillies = date2.getTime() - date1.getTime();
return timeUnit.convert(diffInMillies,TimeUnit.MILLISECONDS);
}
然后你可以打电话:
getDateDiff(date1,date2,TimeUnit.MINUTES);
以分钟为单位获得2个日期的差异。
TimeUnit
是java.util.concurrent.TimeUnit
,标准的Java枚举从纳米到天。