I'm trying to calculate the remaining days to next birthday and setting an alarm to trigger 5 days before.
This is working fine, but it is not accurate.
For example, if I put 23. November 2013 I'm getting 366 days left and if I set some different month from current, I'm getting the right calculation, but not precisely.
For example, if I put 1. December 2013, I'm getting 8 days left and that is 30.
November 2015, not 1. December.
This is what i have done so far:
// Storing selected date
Date dt = null;
try { dt = dateFormatter.parse(dateSelected); } // dateSelected - Variable type String for storing the date user chose
catch (final java.text.ParseException e) { e.printStackTrace(); }
final Calendar BDay = Calendar.getInstance(); // Setting calendar for the next birthday
BDay.setTime(dt); // get selected date of birthday
final Calendar today = Calendar.getInstance(); // Setting calendar for the current date
// Take your DOB Month and compare it to current month
final int BMonth = BDay.get(Calendar.MONTH);
final int CMonth = today.get(Calendar.MONTH);
BDay.set(Calendar.YEAR, today.get(Calendar.YEAR));
// Result of next birthday
if(BMonth <= CMonth)
{
BDay.set(Calendar.YEAR, today.get(Calendar.YEAR) + 1);
}
// Result in millis
final long millis = BDay.getTimeInMillis() - today.getTimeInMillis();
// Convert to days
final long days = millis / 86400000; // Precalculated (24 * 60 * 60 * 1000)
// Test
final long test = today.getTimeInMillis() + 30*1000;
SimpleDateFormat dayFormatter = new SimpleDateFormat("EEEE");
//final String dayOfTheWeek = sdf.format(BDay.getTime());
final String dayOfTheWeek = dayFormatter.format(dt);
if (dateSelected != null) {
Intent intent = new Intent(AddBirthday.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(AddBirthday.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// Set the alarm for a particular time.
// alarmManager.set(AlarmManager.RTC_WAKEUP, test, PendingIntent.getBroadcast(AddBirthday.this, 1 , intent, PendingIntent.FLAG_UPDATE_CURRENT));
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, test, AlarmManager.INTERVAL_DAY, pendingIntent);
}
SuperActivityToast.create(AddBirthday.this, "Days left for birthday: " + days + "\n" + "It will be: " + dayOfTheWeek,
SuperToast.Duration.LONG, Style.getStyle(Style.RED, SuperToast.Animations.FLYIN)).show();