Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current time of day in seconds

Tags:

java

java-time

Is there a way to get the current time of the day in seconds? Notice I am asking the time of the day, not UTC time.

What I want is a value (in seconds) between the range 0 - 86,400 (12:00AM - 11:59PM). I'm working on an app that works on a daily basis, and when the day ends, the time (in seconds) should restart back at 0 again.

So let's say it's 10:00AM. I should be getting 36,000 seconds, and if my time is 5:00PM, I should be getting 61,200 seconds.

PS: I do not know the time before hand. The program will figure it out by itself using a currentTime() function.

like image 991
SVCS1994 Avatar asked Jun 26 '17 19:06

SVCS1994


1 Answers

With Java 8, you could create a Duration instance.
For example :

LocalDateTime date = LocalDateTime.now();
long seconds = Duration.between(date.withSecond(0).withMinute(0).withHour(0), date).getSeconds();

Or more simply you could convert the LocalDateTime to a LocalTime instance and then apply the toSecondOfDay() method :

LocalDateTime date = LocalDateTime.now();
int seconds = date.toLocalTime().toSecondOfDay();

From the java.time.LocalTime javadoc :

public int toSecondOfDay()

Extracts the time as seconds of day, from 0 to 24 * 60 * 60 - 1.

like image 68
davidxxx Avatar answered Sep 21 '22 01:09

davidxxx