我正在尝试计算下一个生日的剩余天数并设置闹钟以便在5天之前触发 这工作正常,但不准确 例如,如果我把23放在2013年11月23日我还剩366天了,如果我从当前设置了一些不同的月份,我会得到正确的计算,但不准确。
例如,如果我把1. 2013年12月,我还剩8天,那就是30 2015年11月,而不是12月。
这是我到目前为止所做的:
// 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();
答案 0 :(得分:0)
你需要清除今天变量中的小时,分钟和秒
示例:
如果今天是2015年11月23日01:00:00而BDay是2015年11月24日00:00:00
millis = xxxx(23小时)
然后
天= millis / 86400000 //预先计算(24 * 60 * 60 * 1000)
天数为0