Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the time since midnight in seconds

Tags:

java

time

clock

First off, this is a simple question that I'm stuck on in my Java 1 class. It's a static time that I set already as 8:49:12 "today" and I'm to figure out how many seconds past midnight and "to" midnight this represents. 8 hours, 49 minutes, and 12 seconds. Here is my code now:

hour    = 8;
minute  = 59;
second  = 32;
System.out.println("The static time used for this program was: " + hour + ":" + minute + ":" + second);

My issue is that I have no clue on how to get the time from and since midnight.

So basically the output needs to be:

Number of seconds since midnight: 
Number of seconds to midnight:

And the space after is for the seconds.

Thanks, and please explain why, and how you chose how to solve this. I want to learn :P

like image 594
TaylorTDHouse Avatar asked Sep 24 '13 06:09

TaylorTDHouse


2 Answers

Try this simple maths :

System.out.println("Number of seconds since midnight:" +(second + (minute*60) + (hour*3600)));
System.out.println("Number of seconds to midnight:" +((60-second) + ((60-1-minute)*60) + (24-1-hour)*3600));
like image 161
Vimal Bera Avatar answered Oct 18 '22 00:10

Vimal Bera


There is an enum in JAVA called TimeUnit that can convert time to any time unit like this:

        int hour    = 8;
        int minute  = 59;
        int second  = 32;
        System.out.println("The static time used for this program was: " + hour + ":" + minute + ":" + second);

        long secInMidnight = TimeUnit.HOURS.toSeconds(24);
        long timeInSeconds = (TimeUnit.HOURS.toSeconds(8) + TimeUnit.MINUTES.toSeconds(minute) + second);

        System.out.println("\nSince midnight: " + timeInSeconds + "\nUntil midnight: " + (secInMidnight - timeInSeconds) );
like image 28
Heisenberg Avatar answered Oct 18 '22 02:10

Heisenberg