36

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.

Shlomo Zalman Heigh
  • 3,968
  • 8
  • 41
  • 71
  • 1
    This might help, just flip it around in your case http://stackoverflow.com/questions/4389500/how-can-i-find-the-amount-of-seconds-passed-from-the-midnight-with-java – squiguy Aug 16 '12 at 14:40

6 Answers6

58

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());
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • 7
    You should be sure to use Calendar.HOUR_OF_DAY and not Calendar.HOUR, because Calendar.HOUR is based on a 12-hour clock. Your midnight calculation might be wrong, depending on what time of day you run the code. I found this out by observation. – Dr. Ferrol Blackmon Jun 14 '13 at 14:24
  • 2
    [`Calendar.getInstance()`](http://developer.android.com/reference/java/util/Calendar.html#getInstance%28%29) is already set to the current date&time, so `c.setTime(now)` is unnecessary. You can also use [`System.currentTimeMillis()`](http://developer.android.com/reference/java/lang/System.html#currentTimeMillis%28%29) to compare with your calendar value – nicopico Jun 14 '13 at 14:42
  • 1
    Hi does your solution require wake lock methods in onReceive method? This: PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Whatever/any tag"); //Acquire the lock wl.acquire(); Log.d("widget", "in alarm manager. static method will come next"); //Release the lock wl.release(); – coolcool1994 Mar 02 '15 at 12:16
  • This will fail on last day of month, you should use add(Calendar.DATE, 1) not DAY_OF_MONTH – Greg Ennis Apr 05 '18 at 20:52
  • @GregEnnis no it won't. Calendar implementation do exactly the same thing for DATE, DAY_OF_MONTH, DAY_OF_YEAR and DAY_OF_WEEK in ̀add` (you can check the sources). – Denys Séguret Apr 06 '18 at 06:10
  • I want to get percentage, but seems System.currentTimeMillis()/c.getTimeInMillis() always give 0.9999.... Dont understand why.... – Boris Legovic Aug 19 '18 at 06:33
24

tl;dr

java.time.Duration
.between( now , tomorrowStart )
.toMillis()

java.time

Java 8 and later comes with the java.time framework built-in. These new classes supplant the old date-time classes (java.util.Date/.Calendar) bundled with Java. Also supplants Joda-Time, developed by the same people. Much of the java.time functionality is back-ported to Java 6 & 7, and further adapted to Android (see below).

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime now = ZonedDateTime.now( z );

We want to get the number of milliseconds running up to, but not including, the first moment of the next day.

We must go through the LocalDate class to get at the first moment of a day. So here we start with a ZonedDateTime to get a LocalDate, and after that get another ZonedDateTime. The key is calling atStartOfDay on the LocalDate.

LocalDate tomorrow = now.toLocalDate().plusDays(1);
ZonedDateTime tomorrowStart = tomorrow.atStartOfDay( z );

Notice that we do not hard-code a time-of-day at 00:00:00. Because of anomalies such as Daylight Saving Time (DST), the day does may start at another time such as 01:00:00. Let java.time determine the first moment.

Now we can calculate elapsed time. In java.time we use the Duration class. The java.time framework has a finer resolution of nanoseconds rather than the coarser milliseconds used by both java.util.Date and Joda-Time. But Duration includes a handy getMillis method, as the Question requested.

Duration duration = Duration.between( now , tomorrowStart );
long millisecondsUntilTomorrow = duration.toMillis();

See this code run live at IdeOne.com.

now.toString(): 2017-05-02T12:13:59.379-04:00[America/Montreal]

tomorrowStart.toString(): 2017-05-03T00:00-04:00[America/Montreal]

millisecondsUntilTomorrow: 42360621


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?


Joda-Time

UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. I leave this section intact for the sake of history, but recommend using java.time and ThreeTenABP as discussed above.

In Android you should be using the Joda-Time library rather than the notoriously troublesome Java.util.Date/.Calendar classes.

Joda-Time offers a milliseconds-of-day command. But we don't really need that here.

Instead we just need a Duration object to represent the span of time until first moment of next day.

Time zone is critical here to determine when "tomorrow" starts. Generally better to specify than rely implicitly on the JVM’s current default time zone which can change at any moment. Or if you really want the JVM’s default, ask for that explicitly with call to DateTimeZone.getDefault to make your code self-documenting.

Could be a two-liner.

DateTime now = DateTime.now( DateTimeZone.forID( "America/Montreal" ) );
long milliSecondsUntilTomorrow = new Duration( now , now.plusDays( 1 ).withTimeAtStartOfDay() ).getMillis();

Let's take that apart.

DateTimeZone zone = DateTimeZone.forID( "America/Montreal" ); // Or, DateTimeZone.getDefault()
DateTime now = DateTime.now( zone );
DateTime tomorrow = now.plusDays( 1 ).withTimeAtStartOfDay();  // FYI the day does not *always* start at 00:00:00.0 time.
Duration untilTomorrow = new Duration( now , tomorrow );
long millisecondsUntilTomorrow = untilTomorrow.getMillis();

Dump to console.

System.out.println( "From now : " + now + " until tomorrow : " + tomorrow + " is " + millisecondsUntilTomorrow + " ms." );

When run.

From now : 2015-09-20T19:45:43.432-04:00 until tomorrow : 2015-09-21T00:00:00.000-04:00 is 15256568 ms.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • You get a big'ol rock on for the java 8 implementation. I had been looking for that for a while. Thank you very much. BTW you should break your answer into a separate answer because it is a little harder to find when the title is Joda. Even though the java 8 spec is very similar. – Chris Hinshaw Feb 23 '16 at 01:41
  • @ChrisHinshaw I revamped this Answer per your suggestion. Moved java.time info up top, marked the Joda-Time section as outdated. – Basil Bourque May 02 '17 at 08:23
2

Try the following:

Calendar c = Calendar.getInstance();
long now = c.getTimeInMillis();
c.add(Calendar.DATE, 1);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);

long millisecondsUntilMidnight = c.getTimeInMillis() - now;

AlarmManager mAlarmManager = (AlarmManager)context.getSystemService(android.content.Context.ALARM_SERVICE);
mAlarmManager.set(AlarmManager.ELAPSED_REALTIME, millisecondsUntilMidnight, mSrvcPendingingIntent);
Korhan Ozturk
  • 11,148
  • 6
  • 36
  • 49
  • 1
    (c.getTimeInMillis - now) will be negative? – sgp15 Aug 16 '12 at 14:47
  • This computes the time to **last** midnight. You must increment the day (see my answer). – Denys Séguret Aug 16 '12 at 14:47
  • I've edited my answer (incremented the day by one). Thanks for warnings. – Korhan Ozturk Aug 16 '12 at 14:49
  • The Documentation shows "SystemClock.elapsedRealtime() + 60 * 1000" to set the alarm with AlarmManager.ELAPSED_REALTIME to one minute in the future. So shouldnt it be "SystemClock.elapsedRealtime() + millisecondsUntilMidnight" in ur example? – Kedu Oct 28 '14 at 19:50
1

Would this work?

long MILLIS_IN_DAY = 86400000;

long currentTime = System.currentTimeInMillis();

long millisTillNow = currentTime % MILLIS_IN_DAY;

long millisecondsUntilMidnight = MILLIS_IN_DAY - millisTillNow;
sgp15
  • 1,280
  • 8
  • 13
0

You could use AlarmManager.RTC instead of AlarmManager.ELAPSED_REALTIME, and just set a Calendar to the time you want :

// Create a calendar for midnight
Calendar todayMidnight = Calendar.getInstance();
todayMidnight.add(Calendar.DATE, 1);
todayMidnight.set(Calendar.HOUR_OF_DAY, 0);
todayMidnight.set(Calendar.MINUTE, 0);
todayMidnight.set(Calendar.SECOND, 0);

// Create an alarm going off at midnight
mAlarmManager.set(
   AlarmManager.RTC, 
   todayMidnight.getTimeInMillis(), 
   mSrvcPendingingIntent
);
nicopico
  • 3,606
  • 1
  • 28
  • 30
  • Hi does your solution require wake lock methods in onReceive method? This: PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Whatever/any tag"); //Acquire the lock wl.acquire(); Log.d("widget", "in alarm manager. static method will come next"); //Release the lock wl.release(); – coolcool1994 Mar 02 '15 at 12:03
  • From the documentation: "The Alarm Manager holds a CPU wake lock as long as the alarm receiver's onReceive() method is executing". So you do not need to handle the wake lock yourself. http://developer.android.com/reference/android/app/AlarmManager.html – nicopico Mar 02 '15 at 13:28
  • How did you do it? Could I have a code snippets? I assume it would be similar for all cases. – coolcool1994 Mar 02 '15 at 23:17
  • How did I do what ? I have feeling you might be better served by creating your own question on Stack Overflow, comments are not really up to the task – nicopico Mar 03 '15 at 10:38
  • My Alarm Manager doesn't update my widget even with wake lock in onReceive: PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE); wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "widgetWL"); wakeLock.acquire(); wakeLock.release() – coolcool1994 Mar 03 '15 at 12:53
0

Using the following way, there is no need to worry about setting DAY_OF_MONTH.

    long msInDay = 86400000;
    Calendar c = Calendar.getInstance();
    c.set(Calendar.HOUR_OF_DAY, 0);
    c.set(Calendar.MINUTE, 0);
    c.set(Calendar.SECOND, 0);
    c.set(Calendar.MILLISECOND, 0);

    System.out.print(msInDay - (System.currentTimeMillis() - c.getTimeInMillis()));
Youness
  • 1,920
  • 22
  • 28