Have a start time and end time that has to be split into equal interval.
E.g.
Start Time: 10AM,
End Time: 14PM,
Split Time: 30 minutes
The output has to be something like this -
::::Output :::
[{time:"10:00"},{time:"10:30"},{time:"11:00"},{time:"11:30"},{time:"12:00"},{time:"12:30"},{time:"13:00"},{time:"13:30"},{time:"14:00"}]
Thanks everyone in advance.
First, convert hours to minutes.
10AM = 10 * 60 minutes
2PM or 14h = 14 * 60 minutes
Then, in order to convert minutes back to hours :
minutes / 60 gives the number of hours
minutes % 60 gives the number of the minutes in the last hour.
If you want to display hours/minutes always on 2 digits, and eventually pad with a leading zero, use :
String result = String.format("%02d", minutes/60);
(2 indicates that you want 2 digits and 0 indicates that you pad with zeros)
That said, there are 2 ways of going from 10*60 to 14*60 with steps of 30 minutes :
The most intuitive : the while loop
public static void interval(int begin, int end, int interval) {
int time = begin;
while (time <= end) {
System.out.println(String.format("%02d:%02d", time / 60, time % 60));
time += interval;
}
}
But I don't like while loops. If you do it wrong (or if the input data are wrong), it ends in infinite loops.
The other way : as you know the begin, the end and the step, use a for loop :
public static void interval2(int begin, int end, int interval) {
for (int time = begin; time <= end; time += interval) {
System.out.println(String.format("%02d:%02d", time / 60, time % 60));
}
}
Test :
interval2(10 * 60, 14 * 60, 30);
Result :
10:00
10:30
11:00
11:30
12:00
12:30
13:00
13:30
14:00
Related
Ok, so I've recently started programming in java about a week ago, and I'm attempting to write a program that will take milliseconds and give me hours, minutes, seconds, and remaining milliseconds. Now I've got most of it down its just for some reason, giving me numbers that are off. I should be getting 2hrs, 46 min, 40 seconds, and 123 milliseconds. But instead I'm getting 2hrs, 2min, 3secs, and 123 milliseconds.
Heres my code
int beginning = 10000123; //beginning is the starting number of milli seconds
int hours = beginning/3600000;
int rSecs = beginning%1000; //r = remaining
int minutes = rSecs/60;
int seconds = rSecs%60;
int milliSecs = rSecs%1000;
System.out.println("Lab03, 100 Point Version\n");
System.out.println("Starting Milliseconds" + beginning);
System.out.println("Hours:" + hours);
System.out.println("Minutes:" + minutes);
System.out.println("Seconds:" + seconds);
System.out.println("Milli Seconds:" + milliSecs);
Thanks for any and all help!
You need to modulo by 3600000 for remaining milli second
int hours = beginning/3600000;
int rMiliSecs = beginning%3600000;
Since it millisecond you need to divide by 60000(1m-> 60s -> 60000ms) for minute and modulo by 60000 to get remainings
int minutes = rMiliSecs/60000;
rMiliSecs = rMiliSecs%60000;
Then divide by 1000 for the second and modulo by 1000(1s -> 1000ms) for remaining millisecond
int seconds = rMiliSecs/1000;
int milliSecs = rMiliSecs%1000;
If you want to avoid the magic numbers and do a more OO approach you can use the Duration class.
Duration duration = Duration.ofMillis(10000123);
long hours = duration.toHours();
duration = duration.minusHours(hours);
long minutes = duration.toMinutes();
duration = duration.minusMinutes(minutes);
long seconds = duration.getSeconds();
duration = duration.minusSeconds(seconds);
long milliSec = duration.toMillis();
This is an exercise question taken from Java Software Solutions: foundations of program design by Lewis & Loftus, 4th edition ; Question PP2.6 (here is a link)
Question is as follows: " Create a project that reads a value representing a number of seconds, then print the equivalent amount of time as a combination of
hours, minutes, and seconds. (For example, 9999 seconds is equivalent
to 2 hours, 46 minutes, and 39 seconds.)"
I have so far tried the following
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
double totalSecs, seconds, minutes, hours;
System.out.println("Enter number of seconds: ");
totalSecs = scan.nextInt();
hours = totalSecs/3600;
minutes = (Math.abs(Math.round(hours)-hours))*60;
seconds = (Math.abs(Math.round(minutes)-minutes))*60;
System.out.print(hours + "\n" + minutes + "\n" + seconds);
}
Answer came out to,
hours: 2.7775
minutes: 13.350000000000009
seconds: 21.00000000000051
What I want to do is take the decimals of, say, hours and multiply them by 60 to get minutes and repeat the process for seconds. I'm however having trouble figuring it out, hence the messy solution of (Math.abs) etc.
What would you recommend me to change/add? Thanks!
Note: This is a book for beginners, hence I've not learned many more operations than those I've already stated in the code. As such, I haven't understood the solution for the previous times this question has been asked.
As an alternative of user2004685's answer;
int seconds = 9999;
int hour = 9999 / (60 * 60); //int variables holds only integer so hour will be 2
seconds = 9999 % (60 * 60); // use modulo to take seconds without hours so it will be 2799
int minute = seconds / 60; //same as int variable so minute will be 49
seconds = seconds % 60; // modulo again to take only seconds
System.out.println(hour + ":" + minute + ":" + seconds);
Here is a much simpler way of doing it:
public static void main (String[] args) throws Exception {
SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss");
TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
System.out.println(sf.format(new Date(9999000)));
}
Note: Please note that this will only show the output in 24-hour format and if number of hours is greater than 24 then it'll increment a day and will start over. For example, 30 hours will be displayed as 06:xx:xx. Also, you'll have to pass the input in milliseconds instead of seconds.
If you want to do it your way then you should probably do something like this:
public static void main (String[] args) throws Exception {
long input = 9999;
long hours = (input - input%3600)/3600;
long minutes = (input%3600 - input%3600%60)/60;
long seconds = input%3600%60;
System.out.println("Hours: " + hours + " Minutes: " + minutes + " Seconds: " + seconds);
}
Output:
Hours: 2 Minutes: 46 Seconds: 39
I've been working on assignment for my homework and I'm stuck again. It's very simple task. (I think so)
For example I have 2493 seconds.
I want to convert it to this format 00:41:33
I know I could use java.utilities but simple maths could solve it too(?)
if(Time>3600) {
Hours = Time/3600;
}
if(Time<3600)
{
Hours = 0;
}
Minutes = ((Time-(3600*Hours))/60);
Seconds = ??????????;
So the only thing I don't get how do I get to know how many seconds left from this thing?
If your Time is given in seconds, you can do the following for your calculation:
int hours = Time / 3600;
int minutes = (Time % 3600) / 60;
int seconds = Time % 60;
The modulus operator gives the remainder after division, and can be used to calculate minutes and seconds.
To calculate minutes, we want to remove all time over 1 hour, so we mod Time by 3600, then we divide by 60.
To calculate seconds, because Time is already in seconds, we mod Time by 60.
Here's the general formula for convertions like this. You do have to remember to subtract the values you have previously converted. For example, after you calculate the hours, you have to subtract the hours so you can then convert the minutes.
public class TimeConverstion
{
private static void convert( int i )
{
int hours = i / 3600;
i = i - hours * 3600;
int minutes = i / 60;
i = i - minutes * 60;
int seconds = i;
System.out.printf( "Hours:%d, minutes:%d, seconds%d%n", hours, minutes,
seconds );
}
public static void main(String[] args) {
convert( 149580 );
}
}
Output of this program:
run:
Hours:41, minutes:33, seconds0
BUILD SUCCESSFUL (total time: 0 seconds)
I have a problem with a program that will tell the time. For example if you ask java what Time(4,129)is, the output should give 6 hours and 9 minutes(Because 129 minute can be simplfied.
Note: This is just a part of my code. I know my code will fail for minute values such as 120,180.
I do understand my forloop is inefficient, but that is not the problem. My problem is that my output for Time(4,129) gives me 4 hours and -51 minutes which is wrong. It should be 6 hours and 9 minutes.
How I think the code is working:
We enter the forloop, go to if statement,check if 129%60 is greater than 0 (9>0) which is true, then proceed.
2.For the body of the if statement, minutes will reduce from 129 to 69 and increment hours by 1 (It is now 5 hours). Forloop ends.
We repeat our forloop which is the 2nd iteration. Check if statement condition ,69%60>0 --> 9>0,True, go to if statement body.
minutes will change to 9 from 69 minutes and hours increment by 1. If statement ends.
Repeat if statement, Third iteration, 9%60 is false therefor if statement does not run.
Time(int x, int y) {
hours = x;
minutes = y;
for (int i = 0; i < 12; i++) {
int temp;
if (minutes % 60 > 0) {
minutes = minutes - 60;
hours = hours++;
Repeat if statement, 9%60 is false therefor if statement does not run
Is it? For minutes being 9, minutes % 60 is 9, which is greater than 0. You want minutes > 59, no modulo needed.
But even easier: hours += minutes / 60; minutes %= 60. No loop required.
It's not clear why you use a loop. But if you insist, how about
while (minutes >= 60) {
minutes -= 60;
hours += 1;
}
Your analysis for the final loop is wrong. 9 % 60 is 9. That's greater than 0 so minutes becomes -51.
This will yield the correct result, the flaw in your code is the use of modulo to figure out when the minutes should be taken into account:
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
int x = 4;
int y = 129;
int hours = x;
int minutes = y;
for (int i = 0; i < 12; i++) {
int temp;
if (minutes > 59) {
minutes = minutes - 60;
hours = ++hours;
}
}
System.out.println("Hours: "+ hours + " minutes: " + minutes);
}
}
I am developing a Java countdown timer. I am totally new to Java though have done some C++ before so it's not all totally new. I am having problems with this - can anyone easily see what I have done wrong in the logic?
What is happening:
On run, if you enter in for example 23 in hours leave mins blank and put in 5 secs - the 5 secs should count to 0 - the mins should go to 59 and the hours to 22. However once the 5 secs elapses all digits go to zero.
If on the input box I enter though 23 hours 1 in minutes and 5 in secs - when the 5 has elapsed it changes to 22 hours 59 mins 59 secs so I know its nearly there (just hoping I may have missed something silly.
Finally the last problem with the logic - if I for example enter 30 mins 5 secs when the 5 have elapsed the mins go to 29 the secs go to 59 and continue counting down but the hours go to -1. Code below - sorry for long post but wanted to paint the scenarios - Thanks - Colly
Integer sec = new Integer (seconds.getText ());
Integer min = new Integer (minutes.getText ());
Integer hr = new Integer (hours.getText ());
int temp1 = sec.intValue ();
int temp2 = min.intValue ();
int temp3 = hr.intValue();
temp1--;
if (temp1 == -1 )
{
temp1 = 59;
temp2--;
if (temp2 == 0 && temp3 != 0)
{
temp2 = 59;
}
temp3--;
}
hr = new Integer (temp3);
sec = new Integer (temp1);
min = new Integer (temp2);
hours.setText (hr.toString ());
minutes.setText (min.toString ());
seconds.setText (sec.toString ());
if (seconds.getText ().length () == 1)
seconds.setText ("0" + seconds.getText ());
Please don't do time counting manually, it is painful to write and painful to read. I don't even mention how it feels to debug it.
The Calendar class may be interesting:
Calendar c = Calendar.getInstance();
c.clear(); // To reset all fields
c.set(Calendar.HOUR_OF_DAY, 23);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 5);
c.add(Calendar.SECOND, -1);
And you don't have to worry about counting.
Using Calendar for date/time is (despite its shortcomings) the right thing. There's a simple alternative here: Compute the total seconds like
int total = 3600 * hrs + 60 * min + sec;
decrement and decompose using
int x = total;
hrs = x / 3600;
x = x - 3600 * hrs;
min = x / 60;
x = x - 60 * min;
sec = x;
This is surely less error-prone than working on the parts, especially for more complicated operations. But again, I recommend using Calendar.
May it's because you are leaving the minutes text box blank. Can you try with a 0 there?
On run, if you enter in for example 23 in hours leave mins blank and
put in 5 secs - the 5 secs should count to 0 - the mins should go to
59 and the hours to 22. However once the 5 secs elapses all digits go
to zero.
I renamed your vars:
s--;
if (s == -1 )
{
s = 59;
m--;
if (m == 0 && h != 0)
{
m = 59;
}
h--;
}
If the seconds are 0, you decrement minutes. Then you test something, but without further tests, you always decrement hours.
While the code doesn't do what it should, it doesn't do what you describe. Is this your real code?