Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

time

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.

like image 840
Utku Zihnioglu Avatar asked Dec 08 '10 16:12

Utku Zihnioglu


People also ask

How to get midnight time in java?

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).

How do you obtain the current second minute and hour Java?

System. out. printf("%d-%02d-%02d %02d:%02d:%02d. %03d", year, month, day, hour, minute, second, millis);

What is Java time 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.


Video Answer


2 Answers

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; 
like image 56
Valentin Rocher Avatar answered Oct 05 '22 05:10

Valentin Rocher


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.

like image 26
Przemek Avatar answered Oct 05 '22 05:10

Przemek