Java: Converting an input of seconds into hours/minutes/seconds - java

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

Related

If Statement not working with double

I am a beginner programmer learning Java. I am doing an exercise where the user enters the number of minutes, and I print out the number of years and days.
I have put together some if statements to print out the amount of years & days, or days only depending on the amount of minutes the user entered.
The if statements fail to work (the first statement gets executed) if the variable year is a double. As soon as I narrow it to an (int) it works fine. I tested it with 2880 minutes, so the value for year should be clearly less than one, and the second if else statement should be executed.
Any help on why this is happening would be appreciated (I am aware that doubles are not totally accurate, but my test case should work as the value for years should be way below 1). Thanks!
import java.util.Scanner;
public class NumberOfYears {
public static void main(String[] args) {
//Set up Scanner object
Scanner input = new Scanner(System.in);
//Get the number of minutes from the user
System.out.print("Enter the number of minutes: ");
int minutes = input.nextInt();
//Determine the amount days / years
double days = minutes / 60.0 / 24;
double years = days / 365.0;
//Print out results
if ( years > 0) {
System.out.println(minutes + " minutes is approximately " + (int) years + " years and " + (int) days % 365
+ " days.");
} else if ( days > 0) {
System.out.println(minutes + " minutes is approximately " + (int) days + " days.");
} else {
System.out.println(minutes + " minutes is less than one day.");
}
}
}
In your if statement, you wrote if (years > 0). Should be if (years > 1). Same with your if (days > 0). Simple as that. There is nothing wrong with floating point math in java or your usage.
I get the following:
Enter the number of minutes: 2880
2880 minutes is approximately 0.005479452054794521 years and 2 days.
code seems to work fine when casting years as a double
I would say the correct approach is to have int types for days and years as well. Then, use integer division (described here) to calculate the number of days and years. There is no reason to have day and year double variables.

Convert time to seconds and then convert it back to hours (JAVA)

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)

convert seconds to H:M:S with "efficiency"

I had to convert seconds to H:M:S, and it was worth 30 points in an exam, however I was docked 3 points for "efficiency". Why?
import javax.swing.JOptionPane;
public class secToMin{
public static void main(String[] args){
int sec, secTotal, hour, min, rem;
secTotal = Integer.parseInt(JOptionPane.showInputDialog("Enter number of seconds"));
if (secTotal<0)
{
System.out.println("invalid input");
System.exit(0);
}
hour = (secTotal/3600);
rem = (secTotal%3600);
min = (rem/60);
sec = (rem%60);
JOptionPane.showMessageDialog(null, secTotal + " equals " + hour + ":" + min + ":" + sec + ".");
System.exit(0);
}
}
The potentially intended solution for the exam may have been to avoid magic numbers like "3600" (OK, it's a well known value, yet, it's a large value).
Instead, Units of time in the International System of Units as defined by the National Institute of Standards and Technology will simply tell you that an hour is "60 minutes" and a minute is "60 seconds".
You can achieve the same conversion steps with:
min = secTotal / 60;
hour = min / 60;
min = min % 60;
sec = secTotal % 60;

Getting minutes from 24 hour time? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I will start with an example: time is 20:00 (2000) and I want to find how many minutes its been since 09:00 (0900), I tried using mod of 60 but this gave me an off time.
Example:
Elapsed time between 1610 1700
1700-1610 = 90, this is obviously wrong
(1700-1610)%60 = 30,
90-30 equals 60, but the answer should be 50. I'm very confused with what I should be doing, how would I go about dealing with this in java? Thanks!
Convert hours to minutes.
1700 hours = 17*60 minutes
1610 hours = 16*60 minutes + 10 minutes
to find out the difference, simple subtraction will do the job
17*60 - 16*60 - 10
Update:
Assuming user enters in 0000 (hhmm) format, you can simply split by size
//psuedo code
String data = userInput;
int hours = Integer.parseInt(data.split(0,2));
int mins = Intger.parseInt(data.split(2,4));
You mixing two representations of the time
13:50
1350 (minutes)
13:50 is 13 hours and 50 minutes, but 1350 is 1350/60 = 22 hours and 1350%60 = 30 minutes
Before you can add, subtract, multiply or divide time you have to convert it to number. In your case:
Elapsed time between 16:10 17:00
16:10 = 16*60+10 = 970
17:00 = 17*60+00 = 1020
17:00 - 16:10 = 1020 - 970 = 50
In Java you could write:
public int minutesFromTime(String time) {
String [] parts = time.split(":");
int hours = Integer.parseInt(parts[0]);
int minutes = Integer.parseInt(parts[1]);
return hours * 60 + minutes;
}
Then
System.out.println("Difference is "
+ (minutesFromTime("17:00") - minutesFromTime("16:10"))
+ " minutes");
To convert your 24-hour time to minutes you need to determine hours and minutes:
int hours = time / 100;
int minutes = time % 100;
And then calculate minutes since midnight:
int minutesSinceMidnight = (hours * 60) + minutes;
You can subtract the minutesSinceMidnight for both times to arrive at the time difference in minutes.
This simple example should do the job:
public static void main(String[] args) {
String after = "2000";
String before = "0900";
int hours = (parseInt(after) - parseInt(before)) / 100;
int minutes = (parseInt(after) % 100) - (parseInt(before) % 100) % 60;
if (minutes < 0) minutes += 60;
System.out.printf("Minutes passed from %s to %s are %d\n", before, after, hours * 60 + minutes);
}
you are dealing with time (60 min), so you can't directly use the math functions (10 base).
So I suggest that you convert your data to Date and then deal with it.
DateFormat dateFormat = new SimpleDateFormat( "HHmm");
Date date = dateFormat.parse("1610");
Date date2 = dateFormat.parse("1700");
long diff = date2.getTime() - date.getTime();
long diffMinutes = diff / (60 * 1000);
You can't do it like this, you are confusing hour and minute as the same unit in your way to do this.
You should separate hour and minute to get the good answer
for example:
String time1 = "1700";
int hour1 = Integer.parseInt(time1.substring(0,2));
int minute1 = Integer.parseInt(time1.substring(2,4));
From int to String to parse
int timeInt = 1715;
String time1 = ""+timeInt;
int hour1 = Integer.parseInt(time1.substring(0,2));
int minute1 = Integer.parseInt(time1.substring(2,4));
Or staying in int
int timeInt = 1715;
int hour = timeInt / 100;
int min = timeInt - hour*100;
If we assume user will always input in XXXX (hhmm) format you can try using this code:
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.print("Enter first time value: ");
int firstTime = userInput.nextInt();
System.out.print("Enter second time value: ");
int secondTime = userInput.nextInt();
int hoursFirst = (int)(firstTime/100);
int minutesFirst = firstTime%100;
int hoursSecond = (int)(secondTime/100);
int minutesSecond = secondTime%100;
int difference = Math.abs((hoursSecond - hoursFirst - 1) * 60 + (60 - minutesFirst) + minutesSecond);
System.out.println("Difference between " + hoursFirst + ":" + minutesFirst
+ " and " + hoursSecond + ":" + minutesSecond + " is " + difference + " minutes.");
}
Output example:
Enter first time value: 1820
Enter second time value: 1610
Difference between 18:20 and 16:10 is 130 minutes.

time difference in military time in Java

So for an assignment we had to write a program that takes two times in military time and shows the difference in hours and minutes between them assuming the first time is the earlier of the two times. We weren't allowed to use if statements as it technically has not be learned. Here's an example of what it'd look like run. In quotes I'll put what is manually entered when it is prompted to.
java MilitaryTime
Please enter first time: "0900"
Please enter second time: "1730"
8 hours 30 minutes (this is the final answer)
I was able to quite easily get this part done with the following code:
class MilitaryTime {
public static void main(String [] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please enter the first time: ");
int FirstTime = in.nextInt();
System.out.println("Please enter the second time: ");
int SecondTime = in.nextInt();
int FirstHour = FirstTime / 100;
int FirstMinute = FirstTime % 100;
int SecondHour = SecondTime / 100;
int SecondMinute = SecondTime % 100;
System.out.println( ( SecondHour - FirstHour ) + " hours " + ( SecondMinute
- FirstMinute ) + " minutes " );
}
}
Now my question is something wasn't assigned (or I wouldn't be here!) is there's another part to this question in the book that says to take that program we just wrote and deal with the case where the first time is later than the second. This has really intrigued me about how this would be done and has really stumped me. Again we aren't allowed to use if statements or this would be easy we basically have all the mathematical functions to work with.
An example would be the first time is now 1730 and the second time is 0900 and so now it returns 15 hours 30 minutes.
I would like to suggest to use org.joda.time.DateTime. There are a lot of date and time functions.
Example :
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy hh:mm");
Date startDate = format.parse("10-05-2013 09:00");
Date endDate = format.parse("11-05-2013 17:30");
DateTime jdStartDate = new DateTime(startDate);
DateTime jdEndDate = new DateTime(endDate);
int years = Years.yearsBetween(jdStartDate, jdEndDate).getYears();
int days = Days.daysBetween(jdStartDate, jdEndDate).getDays();
int months = Months.monthsBetween(jdStartDate, jdEndDate).getMonths();
int hours = Hours.hoursBetween(jdStartDate, jdEndDate).getHours();
int minutes = Minutes.minutesBetween(jdStartDate, jdEndDate).getMinutes();
System.out.println(hours + " hours " + minutes + " minutes");
Your expected program will be as below :
SimpleDateFormat format = new SimpleDateFormat("hhmm");
Dates tartDate = format.parse("0900");
Date endDate = format.parse("1730");
DateTime jdStartDate = new DateTime(startDate);
DateTime jdEndDate = new DateTime(endDate);
int hours = Hours.hoursBetween(jdStartDate, jdEndDate).getHours();
int minutes = Minutes.minutesBetween(jdStartDate, jdEndDate).getMinutes();
minutes = minutes % 60;
System.out.println(hours + " hours " + minutes + " minutes");
Output :
8 hours 30 minutes
Normally, when dealing with time calculations of this nature I would use Joda-Time, but assuming that you don't care about the date component and aren't rolling over the day boundaries, you could simply convert the value to minutes or seconds since midnight...
Basically the problem you have is the simple fact that there are 60 minutes in an hour, this makes doing simple mathematics impossible, you need something which is more common
For example, 0130 is actually 90 minutes since midnight, 1730 is 1050 minutes since midnight, which makes it 16 hours in difference. You can simply subtract the two values to get the difference, then convert that back to hours and minutes...for example...
public class MilTimeDif {
public static void main(String[] args) {
int startTime = 130;
int endTime = 1730;
int startMinutes = minutesSinceMidnight(startTime);
int endMinutes = minutesSinceMidnight(endTime);
System.out.println(startTime + " (" + startMinutes + ")");
System.out.println(endTime + " (" + endMinutes + ")");
int dif = endMinutes - startMinutes;
int hour = dif / 60;
int min = dif % 60;
System.out.println(hour + ":" + min);
}
public static int minutesSinceMidnight(int milTime) {
double time = milTime / 100d;
int hours = (int) Math.floor(time);
int minutes = milTime % 100;
System.out.println(hours + ":" + minutes);
return (hours * 60) + minutes;
}
}
Once you start including the date component or rolling over day boundaries, get Joda-Time out
I would do something like:
System.out.println(Math.abs( SecondHour - FirstHour ) + " hours " + Math.abs( SecondMinute - FirstMinute ) + " minutes " );
The absolute value will give you the difference between the two times as a positive integer.
You could do something like this
//Code like you already have
System.out.println("Please enter the first time: ");
int firstTime = in.nextInt();
System.out.println("Please enter the second time: ");
int secondTime = in.nextInt();
//Now we can continue using the code you already wrote by
//forcing the smaller of the two times into the 'firstTime' variable.
//This forces the problem to be the same situation as you had to start with
if (secondTime < firstTime) {
int temp = firstTime;
firstTime = secondTime;
secondTime = temp;
}
//Continue what you already wrote
There are many other ways but this was something I used for similar problems while learning. Also, note that I changed variable names to follow java naming conventions - variables are lowerCamelCase.
I used 3 classes. Lets go over theory first.
We have two times: A and B.
if AtimeDiff = (B-A).....which can be written -(A-B)
if A>B, then timeDiff = 1440- (A-B) [1440 is total minutes in day]
Thus we need to make timeDiff = 1440 - (A-B) and we need to make 1440 term dissapear when A
Lets make a term X = (A-B+1440) / 1440 (notice "/" is integer division.
'if A
'if A>B then X = 1;
Now look at a new term Y = 1440 * X.
'if A
'if A>B then Y = 1440'.
PROBLEM SOLVED. Now just plug into Java Programs. Note what happens if A=B. Our program will assume we know no time passes if times are exact same time. It assumes that 24 hours have passed. Anyways check out the 3 programs listed below:
Class #1
public class MilitaryTime {
/**
* MilitaryTime A time has a certain number of minutes passed at
* certain time of day.
* #param milTime The time in military format
*/
public MilitaryTime(String milTime){
int hours = Integer.parseInt(milTime.substring(0,2));
int minutes = Integer.parseInt(milTime.substring(2,4));
timeTotalMinutes = hours * 60 + minutes;
}
/**
* Gets total minutes of a Military Time
* #return gets total minutes in day at certain time
*/
public int getMinutes(){
return timeTotalMinutes;
}
private int timeTotalMinutes;
}
Class#2
public class TimeInterval {
/**
A Time Interval is amount of time that has passed between two times
#param timeA first time
#param timeB second time
*/
public TimeInterval(MilitaryTime timeA, MilitaryTime timeB){
// A will be shorthand for timeA and B for timeB
// Notice if A<B timeDifferential = TOTAL_MINUTES_IN_DAY - (A - B)
// Notice if A>B timeDifferential = - (A - B)
// Both will use timeDifferential = TOTAL_MINUTES_IN_DAY - (A - B),
// but we need to make TOTAL_MINUTES_IN_DAY dissapear when needed
//Notice A<B following term "x" is 1 and if A>B then it is 0.
int x = (timeA.getMinutes()-timeB.getMinutes()+TOTAL_MINUTES_IN_DAY)
/TOTAL_MINUTES_IN_DAY;
// Notice if A<B then term "y" is TOTAL_MINUTES_IN_DAY(1440 min)
// and if A<B it is 0
int y = TOTAL_MINUTES_IN_DAY * x;
//yay our TOTAL_MINUTES_IN_DAY dissapears when needed.
int timeDifferential = y - (timeA.getMinutes() - timeB.getMinutes());
hours = timeDifferential / 60;
minutes = timeDifferential % 60;
//Notice that if both hours are equal, 24 hours will be shown.
// I assumed that we would knoe if something start at same time it
// would be "0" hours passed
}
/**
* Gets hours passed between 2 times
* #return hours of time difference
*/
public int getHours(){
return hours;
}
/**
* Gets minutes passed after hours accounted for
* #return minutes remainder left after hours accounted for
*/
public int getMinutes(){
return minutes;
}
private int hours;
private int minutes;
public static final int TOTAL_MINUTES_IN_DAY = 1440;//60minutes in 24 hours
}
Class#3
import java.util.Scanner;
public class MilitaryTimeTester {
public static void main (String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Enter time A: ");
MilitaryTime timeA = new MilitaryTime(in.nextLine());
System.out.println("Enter time B: ");
MilitaryTime timeB = new MilitaryTime(in.nextLine());
TimeInterval intFromA2B = new TimeInterval(timeA,timeB);
System.out.println("Its been "+intFromA2B.getHours()+" hours and "+intFromA2B.getMinutes()+" minutes.");
}
}
import java.util.Scanner;
public class TimeDifference{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// read first time
System.out.println("Please enter the first time: ");
int firstTime = in.nextInt();
// read second time
System.out.println("Please enter the second time: ");
int secondTime = in.nextInt();
in.close();
// if first time is more than second time, then the second time is in
// the next day ( + 24 hours)
if (firstTime > secondTime)
secondTime += 2400;
// first hour & first minutes
int firstHour = firstTime / 100;
int firstMinute = firstTime % 100;
// second hour & second minutes
int secondHour = secondTime / 100;
int secondMinute = secondTime % 100;
// time difference
int hourDiff = secondHour - firstHour;
int minutesDiff = secondMinute - firstMinute;
// adjust negative minutes
if (minutesDiff < 0) {
minutesDiff += 60;
hourDiff--;
}
// print out the result
System.out.println(hourDiff + " hours " + minutesDiff + " minutes ");
}
}
This one is done without using ifs and date thingy. you just need to use integer division "/", integer remainder thing"%", and absolute value and celing. might be able to be simplified but im too lazy at moment. I struggled for hours to figure out and seems nobody else got the answer without using more advanced functions. this problem was in Cay Horstmann's Java book. Chapter 4 in Java 5-6 version of the book "Java Concepts"
import java.util.Scanner;
public class MilitaryTime {
public static void main (String[] args){
//creates input object
Scanner in = new Scanner(System.in);
System.out.println("Enter time A: ");
String timeA = in.next();
System.out.println("Enter time B: ");
String timeB = in.next();
//Gets the hours and minutes of timeA
int aHours = Integer.parseInt(timeA.substring(0,2));
int aMinutes = Integer.parseInt(timeA.substring(2,4));
//Gets the hours and minutes of timeB
int bHours = Integer.parseInt(timeB.substring(0,2));
int bMinutes = Integer.parseInt(timeB.substring(2,4));
//calculates total minutes for each time
int aTotalMinutes = aHours * 60 + aMinutes;
int bTotalMinutes = bHours * 60 + bMinutes;
//timeA>timeB: solution = (1440minutes - (aTotalMinutes - bTotalMinutes))
//timeA<timeB: solution is (bTotalMinutes - aTotalMinutes) or
//-(aTotalMinutes - bTotalMinutes)
//we need 1440 term when timea>timeeB... we use mod and mod remainder
//decider is 1 if timeA>timeB and 0 if opposite.
int decider = ((aTotalMinutes - bTotalMinutes +1440)/1440);
// used 4 Special case when times are equal. this way we get 0
// timeDiffference term when equal and 1 otherwise.
int equalsDecider = (int) Math.abs((aTotalMinutes - bTotalMinutes));
//fullDayMaker is used to add the 1440 term when timeA>timeB
int fullDayMaker = 1440 * decider;
int timeDifference = (equalsDecider)* (fullDayMaker - (aTotalMinutes - bTotalMinutes));
// I convert back to hours and minmutes using modulater
System.out.println(timeDifference/60+" hours and "+timeDifference%60+" minutes");
}
}
java.time
Java 8 and later includes the new java.time framework. See the Tutorial.
The new classes include LocalTime for representing a time-only value without date and without time zone.
Another class is Duration, for representing a span of time as a total number of seconds and nanoseconds. A Duration may be viewed as a number of hours and minutes.
By default the Duration class implements the toString method to generate a String representation of the value using the ISO 8601 format of PnYnMnDTnHnMnS where the P marks the beginning and the T separates the date portion from the time portion. The Duration class can parse as well as generate strings in this standard format.
So, the result in example code below is PT8H30M for eight and a half hours. This format is more sensible than 08:30 which can so easily be confused for a time rather than a duration.
String inputStart = "0900";
String inputStop = "1730";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "HHmm" );;
LocalTime start = formatter.parse ( inputStart , LocalTime :: from );
LocalTime stop = formatter.parse ( inputStop , LocalTime :: from );
Duration duration = Duration.between ( start , stop );
Dump to console.
System.out.println ( "From start: " + start + " to stop: " + stop + " = " + duration );
When run.
From start: 09:00 to stop: 17:30 = PT8H30M
import java.util.*;
class Time
{
static Scanner in=new Scanner(System.in);
public static void main(String[] args)
{
int time1,time2,totalTime;
System.out.println("Enter the first time in military:");
time1=in.nextInt();
System.out.println("Enter the second time in military:");
time2=in.nextInt();
totalTime=time2-time1;
String temp=Integer.toString(totalTime);
char hour=temp.charAt(0);
String min=temp.substring(1,3);
System.out.println(hour+" hours "+min+" minutes");
}
}

Categories

Resources