Getting minutes from 24 hour time? [closed] - java

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.

Related

Java - Adding a 0 in the minutes of the current time (GMT) [duplicate]

This question already has answers here:
How can I pad an integer with zeros on the left?
(18 answers)
Closed 6 years ago.
when I output the following code (taken from dr. Liang Introduction to Java, 10th ed., chapter 03 - selections)
/*
(Current time) Listing 2.7, ShowCurrentTime.java, gives a program that displays
the current time in GMT. Revise the program so that it prompts the user to enter
the time zone offset to GMT and displays the time in the specified time zone.
*/
import java.util.Scanner;
public class Ex_03_08 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the time zone (GMT): ");
int gmt = input.nextInt();
long totalMilliseconds = System.currentTimeMillis();
long totalSeconds = totalMilliseconds / 1000;
long currentSecond = totalSeconds % 60;
long totalMinutes = totalSeconds / 60;
long currentMinute = totalMinutes % 60;
long totalHours = totalMinutes / 60;
long currentHour = totalHours % 24;
currentHour = currentHour + gmt;
System.out.println("The current time is " + currentHour + ":"
+ currentMinute + ":" + currentSecond);
input.close();
}
}
the output is
Enter the time zone (GMT): 1
The current time is 11:2:31
How can I let display instead 11:02:31?
Thank you.
You can do something like this,
String currentMinuteStr=""+currentMinute ;
if(currentMinuteStr.length()==1){
currentMinuteStr="0"+currentMinuteStr;
}
I have just converted the minutes variable to string and then checked whether the length of the string is 1 that is whether it is a one digit minute and then i have appended the existing minutes to 0 and then you can display it as before like this,
System.out.println("The current time is " + currentHour + ":"
+ currentMinuteStr+ ":" + currentSecond);
You can format your input in C style printf using format method.
class NumericFormat
{
public static void main(String[] args) {
System.out.format("%02d%n",3);
//you can use \n too but %n is preferrable for format method
}
}
Get a better understanding at Java Docs
If link fails, here are some of the formatters.
On a side Note, to format and use Date and Time, Java 8 has clean inbuilt API. Get a look at this Oracle tutorial - Date Time Parsing and Formatting
long totalMilliseconds = System.currentTimeMillis();
long totalSeconds = totalMilliseconds / 1000;
long currentSecond = totalSeconds % 60;
long totalMinutes = totalSeconds / 60;
long currentMinute = totalMinutes % 60;
long totalHours = totalMinutes / 60;
long currentHour = totalHours % 24;
currentHour = currentHour + gmt;
String strTime = "" + (currentHour < 10 ? "0" + currentHour : currentHour) +
(currentMinute < 10 ? "0" + currentMinute : currentMinute) +
(currentSecond < 10 ? "0" + currentSecond : currentSecond);
System.out.println("The current time is : " + strTime);

Calculate and Display the Percentage of Time Passed

I'm going through ThinkJava Version 6.1.0 (latest) and in Chapter 2 Exercise 2.3, I'm stuck on #5 which asks "Calculate and display the percentage of the day that has passed. You might run into problems when computing percentages with integers, so consider using floating-point."
I've attempted to get the percentage, but I'm not getting the right result.
I've completed the first 4 questions. Here is what I have so far:
public class Date {
public static void main(String[] args) {
int hour = 13, minute = 58, second = 45;
double percentage;
double secondsSinceMidnight = second + (minute * 60) + (hour * 3600);
double secondsRemainingInDay = (60-second) + ((60-1-minute)*60) + (24-1-hour)*3600;
percentage = (secondsSinceMidnight * 100) / 60;
System.out.println("Number of seconds since midnight:");
System.out.println(secondsSinceMidnight);
System.out.println("Number of seconds remaining in the day:");
System.out.println(secondsRemainingInDay);
System.out.println("Percentage of the day past:");
System.out.println(percentage + "%");
}
}
Thank you for your help and support!
Please check the formula for calculating the percentage of the day already past.
percentage = (secondsSinceMidnight * 100) / 60;
Does not seem right to me. It should be something like
percentage = 100 * secondsSinceMidnight / totalSecondsInDay;
totalSecondsInDay can be the sum of secondsRemainingInDay and secondsSinceMidnight
i think your code have problems with type-casting
in line 3 exchange int with double:
double hour = 13, minute = 58, second = 45;
or there is problem with constant numbers , write numbers in this way : 60.0 instead of 60
Here's an example with a hardcoded time. It's in military time obviously so keep that in mind.
public class Time
{
public static void main(String[] args) {
int startHour = 12; //when you start editing program
int startMinute = 00;
int startSecond = 00;
System.out.print("Number of seconds since midnight: ");
startMinute = (startHour * 60 + startMinute );
startSecond = (startMinute * 60 + startSecond);
System.out.print(startSecond);
System.out.println(" seconds");
int secondInADay = 86400; //number of seconds in a day
System.out.print ("Seconds remaining in the day: ");
System.out.println (secondInADay - startSecond);
System.out.print("Percent of the day that has passed: ");
double startSeconds = 43200; //number of seconds that have passed in a day at start of editing program
System.out.println(startSeconds * 100 / 86400);
int endHour = 16; //time when finished editing program
int endMinute = 00;
int endSecond = 00;
System.out.print ("Difference = "); //difference in time from start to finish
endMinute = (endHour * 60 + endMinute );
endSecond = (endMinute * 60 + endSecond);
System.out.print (endSecond - startSecond);
System.out.print (" 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;

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

Convert seconds value to hours minutes seconds?

I've been trying to convert a value of seconds (in a BigDecimal variable) to a string in an editText like "1 hour 22 minutes 33 seconds" or something of the kind.
I've tried this:
String sequenceCaptureTime = "";
BigDecimal roundThreeCalc = new BigDecimal("0");
BigDecimal hours = new BigDecimal("0");
BigDecimal myremainder = new BigDecimal("0");
BigDecimal minutes = new BigDecimal("0");
BigDecimal seconds = new BigDecimal("0");
BigDecimal var3600 = new BigDecimal("3600");
BigDecimal var60 = new BigDecimal("60");
(I have a roundThreeCalc which is the value in seconds so I try to convert it here.)
hours = (roundThreeCalc.divide(var3600));
myremainder = (roundThreeCalc.remainder(var3600));
minutes = (myremainder.divide(var60));
seconds = (myremainder.remainder(var60));
sequenceCaptureTime = hours.toString() + minutes.toString() + seconds.toString();
Then I set the editText to sequnceCaptureTime String.
But that didn't work. It force closed the app every time. I am totally out of my depth here, any help is greatly appreciated.
Is it necessary to use a BigDecimal? If you don't have to, I'd use an int or long for seconds, and it would simplify things a little bit:
hours = totalSecs / 3600;
minutes = (totalSecs % 3600) / 60;
seconds = totalSecs % 60;
timeString = String.format("%02d:%02d:%02d", hours, minutes, seconds);
You might want to pad each to make sure they're two digit values(or whatever) in the string, though.
DateUtils.formatElapsedTime(long), formats an elapsed time in the form "MM:SS" or "H:MM:SS" . It returns the String you are looking for. You can find the documentation here
You should have more luck with
hours = roundThreeCalc.divide(var3600, BigDecimal.ROUND_FLOOR);
myremainder = roundThreeCalc.remainder(var3600);
minutes = myremainder.divide(var60, BigDecimal.ROUND_FLOOR);
seconds = myremainder.remainder(var60);
This will drop the decimal values after each division.
Edit: If that didn't work, try this. (I just wrote and tested it)
public static int[] splitToComponentTimes(BigDecimal biggy)
{
long longVal = biggy.longValue();
int hours = (int) longVal / 3600;
int remainder = (int) longVal - hours * 3600;
int mins = remainder / 60;
remainder = remainder - mins * 60;
int secs = remainder;
int[] ints = {hours , mins , secs};
return ints;
}
Something really helpful in Java 8
import java.time.LocalTime;
private String ConvertSecondToHHMMSSString(int nSecondTime) {
return LocalTime.MIN.plusSeconds(nSecondTime).toString();
}
Here is the working code:
private String getDurationString(int seconds) {
int hours = seconds / 3600;
int minutes = (seconds % 3600) / 60;
seconds = seconds % 60;
return twoDigitString(hours) + " : " + twoDigitString(minutes) + " : " + twoDigitString(seconds);
}
private String twoDigitString(int number) {
if (number == 0) {
return "00";
}
if (number / 10 == 0) {
return "0" + number;
}
return String.valueOf(number);
}
I prefer java's built in TimeUnit library
long seconds = TimeUnit.MINUTES.toSeconds(8);
private String ConvertSecondToHHMMString(int secondtTime)
{
TimeZone tz = TimeZone.getTimeZone("UTC");
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
df.setTimeZone(tz);
String time = df.format(new Date(secondtTime*1000L));
return time;
}
This is my simple solution:
String secToTime(int sec) {
int seconds = sec % 60;
int minutes = sec / 60;
if (minutes >= 60) {
int hours = minutes / 60;
minutes %= 60;
if( hours >= 24) {
int days = hours / 24;
return String.format("%d days %02d:%02d:%02d", days,hours%24, minutes, seconds);
}
return String.format("%02d:%02d:%02d", hours, minutes, seconds);
}
return String.format("00:%02d:%02d", minutes, seconds);
}
Test Results:
Result: 00:00:36 - 36
Result: 01:00:07 - 3607
Result: 6313 days 12:39:05 - 545488745
If you want the units h, min and sec for a duration you can use this:
public static String convertSeconds(int seconds) {
int h = seconds/ 3600;
int m = (seconds % 3600) / 60;
int s = seconds % 60;
String sh = (h > 0 ? String.valueOf(h) + " " + "h" : "");
String sm = (m < 10 && m > 0 && h > 0 ? "0" : "") + (m > 0 ? (h > 0 && s == 0 ? String.valueOf(m) : String.valueOf(m) + " " + "min") : "");
String ss = (s == 0 && (h > 0 || m > 0) ? "" : (s < 10 && (h > 0 || m > 0) ? "0" : "") + String.valueOf(s) + " " + "sec");
return sh + (h > 0 ? " " : "") + sm + (m > 0 ? " " : "") + ss;
}
int seconds = 3661;
String duration = convertSeconds(seconds);
That's a lot of conditional operators. The method will return those strings:
0 -> 0 sec
5 -> 5 sec
60 -> 1 min
65 -> 1 min 05 sec
3600 -> 1 h
3601 -> 1 h 01 sec
3660 -> 1 h 01
3661 -> 1 h 01 min 01 sec
108000 -> 30 h
I like to keep things simple therefore:
int tot_seconds = 5000;
int hours = tot_seconds / 3600;
int minutes = (tot_seconds % 3600) / 60;
int seconds = tot_seconds % 60;
String timeString = String.format("%02d Hour %02d Minutes %02d Seconds ", hours, minutes, seconds);
System.out.println(timeString);
The result will be: 01 Hour 23 Minutes 20 Seconds
Duration from java.time
BigDecimal secondsValue = BigDecimal.valueOf(4953);
if (secondsValue.compareTo(BigDecimal.valueOf(Long.MAX_VALUE)) > 0) {
System.out.println("Seconds value " + secondsValue + " is out of range");
} else {
Duration dur = Duration.ofSeconds(secondsValue.longValueExact());
long hours = dur.toHours();
int minutes = dur.toMinutesPart();
int seconds = dur.toSecondsPart();
System.out.format("%d hours %d minutes %d seconds%n", hours, minutes, seconds);
}
Output from this snippet is:
1 hours 22 minutes 33 seconds
If there had been a non-zero fraction of second in the BigDecimal this code would not have worked as it stands, but you may be able to modify it. The code works in Java 9 and later. In Java 8 the conversion from Duration into hours minutes and seconds is a bit more wordy, see the link at the bottom for how. I am leaving to you to choose the correct singular or plural form of the words (hour or hours, etc.).
Links
Oracle tutorial: Date Time explaining how to use java.time.
Answer by lauhub showing the conversion from a Duration to days, hours, minutes and seconds in Java 8.
This Code Is working Fine :
txtTimer.setText(String.format("%02d:%02d:%02d",(SecondsCounter/3600), ((SecondsCounter % 3600)/60), (SecondsCounter % 60)));
A nice and easy way to do it using GregorianCalendar
Import these into the project:
import java.util.GregorianCalendar;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.Scanner;
And then:
Scanner s = new Scanner(System.in);
System.out.println("Seconds: ");
int secs = s.nextInt();
GregorianCalendar cal = new GregorianCalendar(0,0,0,0,0,secs);
Date dNow = cal.getTime();
SimpleDateFormat ft = new SimpleDateFormat("HH 'hours' mm 'minutes' ss 'seconds'");
System.out.println("Your time: " + ft.format(dNow));
for just minutes and seconds use this
String.format("%02d:%02d", (seconds / 3600 * 60 + ((seconds % 3600) / 60)), (seconds % 60))
With Java 8, you can easily achieve time in String format from long seconds like,
LocalTime.ofSecondOfDay(86399L)
Here, given value is max allowed to convert (upto 24 hours) and result will be
23:59:59
Pros : 1) No need to convert manually and to append 0 for single digit
Cons : work only for up to 24 hours
I use this:
public String SEG2HOR( long lnValue) { //OK
String lcStr = "00:00:00";
String lcSign = (lnValue>=0 ? " " : "-");
lnValue = lnValue * (lnValue>=0 ? 1 : -1);
if (lnValue>0) {
long lnHor = (lnValue/3600);
long lnHor1 = (lnValue % 3600);
long lnMin = (lnHor1/60);
long lnSec = (lnHor1 % 60);
lcStr = lcSign + ( lnHor < 10 ? "0": "") + String.valueOf(lnHor) +":"+
( lnMin < 10 ? "0": "") + String.valueOf(lnMin) +":"+
( lnSec < 10 ? "0": "") + String.valueOf(lnSec) ;
}
return lcStr;
}
Here's my function to address the problem:
public static String getConvertedTime(double time){
double h,m,s,mil;
mil = time % 1000;
s = time/1000;
m = s/60;
h = m/60;
s = s % 60;
m = m % 60;
h = h % 24;
return ((int)h < 10 ? "0"+String.valueOf((int)h) : String.valueOf((int)h))+":"+((int)m < 10 ? "0"+String.valueOf((int)m) : String.valueOf((int)m))
+":"+((int)s < 10 ? "0"+String.valueOf((int)s) : String.valueOf((int)s))
+":"+((int)mil > 100 ? String.valueOf((int)mil) : (int)mil > 9 ? "0"+String.valueOf((int)mil) : "00"+String.valueOf((int)mil));
}
I know this is pretty old but in java 8:
LocalTime.MIN.plusSeconds(120).format(DateTimeFormatter.ISO_LOCAL_TIME)
I use this in python to convert a float representing seconds to hours, minutes, seconds, and microseconds. It's reasonably elegant and is handy for converting to a datetime type via strptime to convert. It could also be easily extended to longer intervals (weeks, months, etc.) if needed.
def sectohmsus(seconds):
x = seconds
hmsus = []
for i in [3600, 60, 1]: # seconds in a hour, minute, and second
hmsus.append(int(x / i))
x %= i
hmsus.append(int(round(x * 1000000))) # microseconds
return hmsus # hours, minutes, seconds, microsecond
i have tried the best way and less code but may be it is little bit difficult to understand how i wrote my code but if you good at maths it is so easy
import java.util.Scanner;
class hours {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double s;
System.out.println("how many second you have ");
s =input.nextInt();
double h=s/3600;
int h2=(int)h;
double h_h2=h-h2;
double m=h_h2*60;
int m1=(int)m;
double m_m1=m-m1;
double m_m1s=m_m1*60;
System.out.println(h2+" hours:"+m1+" Minutes:"+Math.round(m_m1s)+" seconds");
}
}
more over it is accurate !
Tough there are yet many correct answers and an accepted one, if you want a more handmade and systematized way to do this, I suggest something like this:
/**
* Factors for converting seconds in minutes, minutes in hours, etc.
*/
private static int[] FACTORS = new int[] {
60, 60, 24, 7
};
/**
* Names of each time unit.
* The length of this array needs to be FACTORS.length + 1.
* The last one is the name of the remainder after
* obtaining each component.
*/
private static String[] NAMES = new String[] {
"second", "minute", "hour", "day", "week"
};
/**
* Checks if quantity is 1 in order to use or not the plural.
*/
private static String quantityToString(int quantity, String name) {
if (quantity == 1) {
return String.format("%d %s", quantity, name);
}
return String.format("%d %ss", quantity, name);
}
/**
* The seconds to String method.
*/
private static String secondsToString(int seconds) {
List<String> components = new ArrayList<>();
/**
* Obtains each component and stores only if is not 0.
*/
for (int i = 0; i < FACTORS.length; i++) {
int component = seconds % FACTORS[i];
seconds /= FACTORS[i];
if (component != 0) {
components.add(quantityToString(component, NAMES[i]));
}
}
/**
* The remainder is the last component.
*/
if (seconds != 0) {
components.add(quantityToString(seconds, NAMES[FACTORS.length]));
}
/**
* We have the non-0 components in reversed order.
* This could be extracted to another method.
*/
StringBuilder builder = new StringBuilder();
for (int i = components.size() - 1; i >= 0; i--) {
if (i == 0 && components.size() > 1) {
builder.append(" and ");
} else if (builder.length() > 0) {
builder.append(", ");
}
builder.append(components.get(i));
}
return builder.toString();
}
The result is as following:
System.out.println(secondsToString(5_000_000)); // 8 weeks, 1 day, 20 hours, 53 minutes and 20 seconds
System.out.println(secondsToString(500_000)); // 5 days, 18 hours, 53 minutes and 20 seconds
System.out.println(secondsToString(60*60*24)); // 1 day
System.out.println(secondsToString(2*60*60*24 + 3*60)); // 2 days and 3 minutes
System.out.println(secondsToString(60*60*24 + 3 * 60 * 60 + 53)); // 1 day, 3 hours and 53 seconds
You can get this done easily using method overloading.
Here's a code I wrote to convert seconds to hours, minutes and seconds format.
public class SecondsAndMinutes {
public static void main(String[] args) {
String finalOutput = getDurationString(-3666);
System.out.println(finalOutput);
}
public static String getDurationString(int seconds) {
if(seconds <= 0) {
return "Add a value bigger than zero.";
}else {
int hours = seconds / (60*60);
int remainingOneSeconds = seconds % (60*60);
int minutes = remainingOneSeconds / 60;
int remainingSeconds = remainingOneSeconds % 60;
String x = Integer.toString(hours);
return x+"h " + getDurationString(minutes, remainingSeconds);
}
}
public static String getDurationString(int minutes, int seconds) {
if(seconds <= 0 && seconds > 59) {
return "Seconds needs to be within 1 to 59";
}else {
String y = Integer.toString(minutes);
String z = Integer.toString(seconds);
return y+"m "+z+"s";
}
}
}

Categories

Resources