Reputation: 1
when I try to calculate the days for birthday always gives me the wrong number of days
Can you help me what is wrong?
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"));
This is the first part of the code:
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);
Upvotes: 0
Views: 428
Reputation: 7214
Use the following method to find the difference between two dates.
/**
* 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);
}
And then can you call:
getDateDiff(date1,date2,TimeUnit.MINUTES);
to get the diff of the 2 dates in minutes unit.
TimeUnit
is java.util.concurrent.TimeUnit
, a standard Java enum going from nanos to days.
Upvotes: 2