Get milliseconds until midnight

28,713

Solution 1

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());

Solution 2

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.

Solution 3

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);

Solution 4

Would this work?

long MILLIS_IN_DAY = 86400000;

long currentTime = System.currentTimeInMillis();

long millisTillNow = currentTime % MILLIS_IN_DAY;

long millisecondsUntilMidnight = MILLIS_IN_DAY - millisTillNow;
Share:
28,713
SZH
Author by

SZH

Updated on January 21, 2021

Comments

  • SZH
    SZH over 3 years

    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.

  • Denys Séguret
    Denys Séguret almost 12 years
    Hum. I don't think this deals with reality (spare seconds, and so on).
  • sgp15
    sgp15 almost 12 years
    (c.getTimeInMillis - now) will be negative?
  • Denys Séguret
    Denys Séguret almost 12 years
    This computes the time to last midnight. You must increment the day (see my answer).
  • Korhan Ozturk
    Korhan Ozturk almost 12 years
    I've edited my answer (incremented the day by one). Thanks for warnings.
  • Dr. Ferrol Blackmon
    Dr. Ferrol Blackmon about 11 years
    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.
  • nicopico
    nicopico about 11 years
    Calendar.getInstance() is already set to the current date&time, so c.setTime(now) is unnecessary. You can also use System.currentTimeMillis() to compare with your calendar value
  • Kedu
    Kedu over 9 years
    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?
  • coolcool1994
    coolcool1994 over 9 years
    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
    coolcool1994 over 9 years
    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();
  • nicopico
    nicopico over 9 years
    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. developer.android.com/reference/android/app/AlarmManager.htm‌​l
  • coolcool1994
    coolcool1994 over 9 years
    How did you do it? Could I have a code snippets? I assume it would be similar for all cases.
  • nicopico
    nicopico over 9 years
    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
  • coolcool1994
    coolcool1994 over 9 years
    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()
  • Chris Hinshaw
    Chris Hinshaw over 8 years
    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.
  • Basil Bourque
    Basil Bourque about 7 years
    @ChrisHinshaw I revamped this Answer per your suggestion. Moved java.time info up top, marked the Joda-Time section as outdated.
  • Greg Ennis
    Greg Ennis about 6 years
    This will fail on last day of month, you should use add(Calendar.DATE, 1) not DAY_OF_MONTH
  • Denys Séguret
    Denys Séguret about 6 years
    @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).
  • Boris Legovic
    Boris Legovic almost 6 years
    I want to get percentage, but seems System.currentTimeMillis()/c.getTimeInMillis() always give 0.9999.... Dont understand why....