Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the milliseconds to the next hour

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.

like image 218
Subhakant Priyadarsan Avatar asked Oct 02 '18 04:10

Subhakant Priyadarsan


People also ask

How do you convert milliseconds to hours in Java?

24 hours = 86400 seconds = 86400000 milliseconds. Just multiply your number with 86400000.

How do you convert milliseconds to days hours minutes seconds in Java?

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.

How do you calculate milliseconds in Java?

currentTimeMillis() method returns the current time in milliseconds.


2 Answers

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.

like image 94
xingbin Avatar answered Sep 22 '22 12:09

xingbin


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.

like image 31
LuCio Avatar answered Sep 19 '22 12:09

LuCio