TaylorTDHouse TaylorTDHouse -3 years ago 96
Java Question

How to get the time since midnight in seconds

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

Answer Source

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));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download