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