How can I find the amount of seconds passed from the midnight with Java?

If you're using Java >= 8, this is easily done :

ZonedDateTime nowZoned = ZonedDateTime.now();
Instant midnight = nowZoned.toLocalDate().atStartOfDay(nowZoned.getZone()).toInstant();
Duration duration = Duration.between(midnight, Instant.now());
long seconds = duration.getSeconds();

If you're using Java 7 or less, you have to get the date from midnight via Calendar, and then substract.

Calendar c = Calendar.getInstance();
long now = c.getTimeInMillis();
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
long passed = now - c.getTimeInMillis();
long secondsPassed = passed / 1000;

java.time

Using the java.time framework built into Java 8 and later. See Tutorial.

import java.time.LocalTime
import java.time.ZoneId

LocalTime now = LocalTime.now(ZoneId.systemDefault()) // LocalTime = 14:42:43.062
now.toSecondOfDay() // Int = 52963

It is good practice to explicit specify ZoneId, even if you want default one.

Tags:

Time

Java