I want to the milliseconds to the next hours. For example
Now time -> 10:01:23 2nd Oct, 2018, Want remaining milliseconds to 11:00:00 2nd Oct, 2018.
The Now time is dynamic, it can be 23:56:56 2nd Oct, 2018 and next hour is at 00:00:00 3rd Oct, 2018.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(startDate.getMillis());
calendar.add(Calendar.HOUR, 1);
I was trying something like this, but it is adding 1 hour to the startDate. But I want exact next hour.
Any help is welcomed.
24 hours = 86400 seconds = 86400000 milliseconds. Just multiply your number with 86400000.
Save this answer. Show activity on this post. long seconds = timeInMilliSeconds / 1000; long minutes = seconds / 60; long hours = minutes / 60; long days = hours / 24; String time = days + ":" + hours % 24 + ":" + minutes % 60 + ":" + seconds % 60; Save this answer.
currentTimeMillis() method returns the current time in milliseconds.
Since Java8, you can use java.time.LocalDateTime
:
LocalDateTime start = LocalDateTime.now();
// Hour + 1, set Minute and Second to 00
LocalDateTime end = start.plusHours(1).truncatedTo(ChronoUnit.HOURS);
// Get Duration
Duration duration = Duration.between(start, end);
long millis = duration.toMillis();
Running just now (2018-10-02T18:44:48.943070 Peking time) I got 911 056 milliseconds.
A simple arithmetic approach:
long hourInMillis = 60 * 60 * 1000;
long startDateInMillis = startDate.getMillis();
long millisSinceLastHourChange = startDateInMillis % hourInMillis;
long millisToNextHourChange = hourInMillis - millisSinceLastHourChange;
works since Java 1 ;-)
EDIT
This approach doesn't take DST or similar changes into account.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With