Time maths is inherently inaccurate. There are lots of "rules" and "edge cases" which don't make it as simple as adding or multiplying seconds together. Instead, you should be making use of appropriate libraries which support these things.
Post Java 8
How time flies ...
Make use of the java.time
APIs, for example...
LocalDateTime before = LocalDateTime
.now()
.withHour(0)
.withMinute(0)
.withSecond(0)
.withNano(0);
LocalDateTime after = before
.now()
.withHour(23)
.withMinute(59)
.withSecond(59)
.withNano(999_999_999);
LocalDateTime now = LocalDateTime.now();
Duration duration = Duration.between(before, now);
DateTimeFormatter formatter = DateTimeFormatter.ISO_TIME;
System.out.println("Seconds from midnight to " + formatter.format(now) + " = " + Duration.between(before, now).toSeconds());
System.out.println("Seconds to midnight from " + formatter.format(now) + " = " + Duration.between(now, after).toSeconds());
Which outputs...
Seconds from midnight to 09:55:21.308052 = 35721
Seconds to midnight from 09:55:21.308052 = 50678
Pre Java 8
Use the ThreeTen BackPort, no, seriously, get the java.time
APIs in earlier versions of Java
JodaTime (I believe this is now in maintaince)
Or you could use JodaTime...
MutableDateTime now = MutableDateTime.now();
now.setMillisOfDay(0);
now.setSecondOfDay(32);
now.setMinuteOfDay(59);
now.setHourOfDay(8);
DateTime fromMidnight = now.toDateTime().toDateMidnight().toDateTime();
DateTime toMidnight = fromMidnight.plusDays(1);
Duration duration = new Duration(fromMidnight, toMidnight);
Duration dFromMidnight = new Duration(fromMidnight, now);
System.out.println("From midnight: " + dFromMidnight.getStandardSeconds());
Duration dToMidnight = new Duration(now, toMidnight);
System.out.println("To Midnight: " + dToMidnight.getStandardSeconds());
Which outputs...
From midnight: 32372
To Midnight: 54028
Calendar
(don't do this)
Given the idiosyncrasies of time, you could simply use the Calendar
API
Calendar fromMidnight = Calendar.getInstance();
fromMidnight.set(Calendar.HOUR, 0);
fromMidnight.set(Calendar.MINUTE, 0);
fromMidnight.set(Calendar.SECOND, 0);
fromMidnight.set(Calendar.MILLISECOND, 0);
Calendar toMidnight = Calendar.getInstance();
toMidnight.setTime(fromMidnight.getTime());
toMidnight.add(Calendar.DATE, 1);
System.out.println(fromMidnight.getTime());
System.out.println(toMidnight.getTime());
Calendar toFromTime = Calendar.getInstance();
toFromTime.set(Calendar.HOUR, 8);
toFromTime.set(Calendar.MINUTE, 59);
toFromTime.set(Calendar.SECOND, 32);
toFromTime.set(Calendar.MILLISECOND, 0);
long secondsFromMidnight = (toFromTime.getTimeInMillis() - fromMidnight.getTimeInMillis()) / 1000;
long secondsToMidnight = (toMidnight.getTimeInMillis() - toFromTime.getTimeInMillis()) / 1000;
System.out.println("from = " + secondsFromMidnight + "; to " + secondsToMidnight);
Which outputs...
from = 32372; to 54028