Get milliseconds until midnight

SZH picture SZH · Aug 16, 2012 · Viewed 27k times · Source

I'm creating an Android widget that I want to update every night at midnight. I am using an AlarmManager and I need to find out how many milliseconds are left from the current time until midnight. Here's my code:

AlarmManager mAlarmManager = (AlarmManager)context.getSystemService(android.content.Context.ALARM_SERVICE);
mAlarmManager.set(AlarmManager.ELAPSED_REALTIME, millisecondsUntilMidnight, mSrvcPendingingIntent);

How can I calculate how many milliseconds are left until midnight?

Thank you in advance.

Answer

Denys Séguret picture Denys Séguret · Aug 16, 2012

Use a Calendar to compute it :

        Calendar c = Calendar.getInstance();
        c.add(Calendar.DAY_OF_MONTH, 1);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        long howMany = (c.getTimeInMillis()-System.currentTimeMillis());