I need a function that gives me how many seconds passed from the midnight. I am currently using System.currentTimeMillis()
but it gives me the UNIX like timestamp.
It would be a bonus for me if I could get the milliseconds too.
LocalDateTime startOfDay = LocalDateTime. of(localDate, LocalTime. MIDNIGHT); LocalTime offers the following static fields: MIDNIGHT (00:00), MIN (00:00), NOON (12:00), and MAX(23:59:59.999999999).
System. out. printf("%d-%02d-%02d %02d:%02d:%02d. %03d", year, month, day, hour, minute, second, millis);
currentTimeMillis() method returns the current time in milliseconds. The unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.
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;
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.
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