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
Would this work?
long MILLIS_IN_DAY = 86400000;
long currentTime = System.currentTimeInMillis();
long millisTillNow = currentTime % MILLIS_IN_DAY;
long millisecondsUntilMidnight = MILLIS_IN_DAY - millisTillNow;
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
);
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()));
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());
Duration.between( now , tomorrowStart )
.toMillis()
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
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?
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.
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);