时间又到了上午10点



我每天都在上午10点尝试发布通知。通知已经每天发送,但不是在上午 10 点发送,所以我需要计算等待时间,直到我的 AlarmManager 再次达到上午 10 点。

DateFormat dateFormat = new SimpleDateFormat("HH:mm");
long target = dateFormat.parse("10:00").getTime();

我试过这个,但我得到的时间戳是 50 年前左右......(我认为这是时间戳开始计数后第一次上午 10 点的时间(

那么如何计算等待到上午 10 点的毫秒数呢?

出于时间操作目的,请使用Calendar而不是SimpleDateFormat

为了找到第二天上午10点:

final Calendar c = Calendar.getInstance()
c.set(Calendar.HOUR_OF_DAY, 10) // For 10AM
c.add(Calendar.DATE, 1) // Add 1 to date == tomorrow
final Date d = c.getTime()
// Do what you want with the date

您应该采用一个日历对象并将一天中的小时设置为上午 10 点,而不是从该日历对象(如 calender.getTime(( (获取时间,它将返回很长的时间,并且在设置警报管理器时将其设置为 setRepeating(calender.getTime(((。

最新更新