Converting the left over decminal to weeks, days, hours, min, seconds - java

Right now I am finding out 25% of a persons years and for example if you had 5 years 25% is 1.25. Though the plugin im making cant remove 1.25 years from you the .25 needs to be converted to weeks and then any leftovers to days and so on. Though I dont know how I would convert these times.
Integer y = itapi.getPlayerYears(player.getName());
Double yremove = Integer.valueOf(y) * 0.25;
Integer w = itapi.getPlayerWeeks(player.getName());
Double wremove = Integer.valueOf(w) * 0.25;
Integer d = itapi.getPlayerDays(player.getName());
Double dremove = Integer.valueOf(d) * 0.25;
Integer h = itapi.getPlayerHours(player.getName());
Double hremove = Integer.valueOf(h) * 0.25;
Integer m = itapi.getPlayerMinutes(player.getName());
Double mremove = Integer.valueOf(m) * 0.25;
Integer s = itapi.getPlayerSeconds(player.getName());
Double sremove = Integer.valueOf(s) * 0.25;
String yminus = String.valueOf(yremove) + 'y';
String wminus = String.valueOf(wremove) + 'w';
String dminus = String.valueOf(dremove) + 'd';
String hminus = String.valueOf(hremove) + 'h';
String mminus = String.valueOf(mremove) + 'm';
String sminus = String.valueOf(sremove) + 's';
ItemStack book = itapi.createTimeCard("Death of " + player.getName(), yminus + wminus + dminus + hminus + mminus + sminus, 1);
itapi.removeTime(player.getName(), yminus + wminus + dminus + hminus + mminus + sminus );
e.getDrops().add(book);
Would it be possible to work the conversion out or would it be better to convert all time to seconds then take 25% and convert it back?

I would use nested ifs and pass the remainder around. I have not tested this but it should give you an idea.
Integer y = itapi.getPlayerYears(player.getName());
double yremove = Integer.valueOf(y) *0.25;
double numWeeks = yremove * 52; //returns the number in weeks
double numDays =0;
double numHours =0;
double numMinutes =0;
double numSeconds =0;
if(numWeeks % 52 != 0){
numDays = (numWeeks % 52) * 7;
if(numDays % 7 !=0){
numHours = (numDays % 7) * 24;
if(numHours % 24 !=0){
numMinutes = (numHours % 24) * 60;
if(numMinutes % 60 !=0){
numSeconds = (numMinutes % 60) * 60;
}
}
}
}
//... then convert to string as you are already doing and pass it to removeTime()

You can use Calendar class to calculate this for you, something like:
Calendar c = Calendar.getInstance();
double millis = 1.25 * 31557600 * 1000;
long l = (long) millis;
c.setTimeInMillis(l);
System.out.println(c.get(Calendar.YEAR) + " Year");
System.out.println(c.get(Calendar.MONTH) + " months");
System.out.println(c.get(Calendar.WEEK_OF_MONTH) + " weeks");
System.out.println(c.get(Calendar.DAY_OF_MONTH) + " days");
System.out.println(c.get(Calendar.HOUR) + " hours");
System.out.println(c.get(Calendar.MINUTE) + " minutes");
System.out.println(c.get(Calendar.SECOND) + " seconds");
Output:
1971 Year
3 months
1 weeks
2 days
7 hours
0 minutes
0 seconds
Calendar defaults the starting year to 1970, you can further manipulate year and months to weeks if need be.

Create a class to manage time. This class will have methods to return time in terms of years, weeks, months, etc.
public class Time{
private long milliseconds;
public double getSeconds(){
double seconds = milliseconds/1000.0;
return seconds;
}
public void subtractSeconds(double seconds){
long millisInSeconds = (long)(seconds*1000);
this.millisecionds -= millisInSeconds;
}
//write more methods for years, months etc.
}
Then, use this class to retrieve years, months, weeks and subtract the difference. This will keep your code clean, and easy to understand.
Time time = new Time(1000*60*60);
int years = (int)time.getYears();
time.subtractYears(years);
int months = (int)time.getMonths();
time.subtractMonths(months);

Related

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

Calculate days between two dates without using any date class

I am trying to right a program for my introduction to java course. The user enters their birthdate in the following format(19900506), the amount of days the person is then displayed. The program uses the GregorianCalendar class to get today's date and compares the two. Leap years are taken into account. I was able to right the program, but I need to write another version that calculates the difference using my own algorithm. I have hit a wall and can't figure out how to do this. I was thinking of converting the difference between the two dates to milliseconds and then converting to days again. But there is a lot of things to be considerd, like days in months, days remaining from todays date, etc. Any help would be appreciated.
Here is my code:
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Scanner;
public class DayssinceBirthV5 {
public static void main(String[] args) {
GregorianCalendar greg = new GregorianCalendar();
int year = greg.get(Calendar.YEAR);
int month = greg.get(Calendar.MONTH);
int day = greg.get(Calendar.DAY_OF_MONTH);
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your birthday: AAAAMMDD): ");
int birthday = keyboard.nextInt();//
int testyear = birthday / 10000;// year
int testmonth = (birthday / 100) % 100;// Month
int testday = birthday % 100;// Day
int counter = calculateLeapYears(year, testyear);
GregorianCalendar userInputBd = new GregorianCalendar(testyear, testmonth - 1, testday);// Input
long diffSec = (greg.getTimeInMillis() - userInputBd.getTimeInMillis());// Räkna ut diff
// long diffSec = greg.get(Calendar.YEAR)-birthday;//calc Diff
long total = diffSec / 1000 / 60 / 60 / 24;// calc dif in sec. Sec/min/hours/days
total += counter;
System.out.println("Today you are : " + total + " days old");
}
private static int calculateLeapYears(int year, int testyear) {
int counter = 0;
for (int i = testyear; i < year; i++) {
if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {
counter++;
System.out.println("Amount of leap years: " + counter);
}
}
return counter;
}
}
You can calculate the number of days like this -
Write a method that finds the number of days in a year: Leap years have 366 days, non-leap years have 365.
Write another method that gets a date and finds the day of year - January 1st is day 1, January 2nd is day 2 and so on. You'll have to use the function from 1.
Calculate the following:
Number of days until year's end from date of birth.
Number of days from year's begining until current date.
Numer of days of all years between.
Sum up all of the above.
def daysBetweenDates(self, date1: str, date2: str) -> int:
y1, m1, d1 = map(int, date1.split('-'))
y2, m2, d2 = map(int, date2.split('-'))
m1 = (m1 + 9) % 12
y1 = y1 - m1 // 10
x1= 365*y1 + y1//4 - y1//100 + y1//400 + (m1*306 + 5)//10 + ( d1 - 1 )
m2 = (m2 + 9) % 12
y2 = y2 - m2 // 10
x2= 365*y2 + y2//4 - y2//100 + y2//400 + (m2*306 + 5)//10 + ( d2 - 1 )
return abs(x2 - x1)

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.

When compiling, I receive the error: "unreachable statement". How can I fix the issue?

public double Convertir(double Number) {
Number = nombre;
while ((Number - 365) >= 0) {
annee += 1; //this calculates the number of years
}
return annee;
double nombreSemaine = Number - (annee * 365);
while ((nombreSemaine - 7) >= 0) {
semaine = semaine + 1;
}//this calculates the number of weeks
return semaine;
double nombreJour = Number - (annee * 365) - (semaine * 7);
nombreJour = jour;
return jour;
}
With this code I am trying to convert a number written by the user,
which are days, into the number of years that it makes, the number of
weeks and the number of days. for example, number 365 should return 1
year 0 weeks 0 days.
return annee; returns annee so anything after this expression in the method won't get executed.
Perhaps you could return an Array instead:
public double[] Convertir(double Number) {
Number = nombre;
double[] all = new double[3];
while ((Number - 365) >= 0) {
annee += 1; //this calculates the number of years
}
all[0] = annee;
double nombreSemaine = Number - (annee * 365);
while ((nombreSemaine - 7) >= 0) {
semaine = semaine + 1;
}//this calculates the number of weeks
all[1] = semaine;
double nombreJour = Number - (annee * 365) - (semaine * 7);
nombreJour = jour;
all[2] = jour;
return all
}
or something similar. An ArrayList would probably be better...but it's the same general concept.
The code below return annee; won't be executed.
It looks like you want to return 3 values. You can only return 1 value, a double in this case.
Solution 1 (Global variables):
int annee, semaine, jour; //global variables
public void Convertir(int Number) { //I guess number should be an Int too, unless it's possible to pass 567.28 days...
//Number = nombre; Useless since this is a parameter
annee = (int)(Number/365);
semaine = (int)((Number - annee * 365)/7);
jour = Number - annee * 365 - semaine * 7;
}
Solution 2 (return an array):
public int[] Convertir(int Number) { //I guess number should be an Int too, unless it's possible to pass 567.28 days...
//Number = nombre; Useless since this is a parameter
int[] anneeSemaineJour = new int[3];
anneeSemaineJour[0] = (int)(Number/365);
anneeSemaineJour[1] = (int)((Number - anneeSemaineJour[0] * 365)/7);
anneeSemaineJour[2] = Number - anneeSemaineJour[0] * 365 - anneeSemaineJour[1] * 7;
return anneeSemaineJour;
}
You will then use it like this (Solution 2):
int[] resultat = convertir(822); // convertir(nombre) in your case I guess
System.out.println("Annee = " + resultat[0] + " Semaine = " + resultat[1] + " Jour = " + resultat[2]);
The problem is you have code (including another return) after a return statement. A return statement stops the function at that place and returns the value. Anything after that is unreachable.
Your code suffers from many problems.
Beside all what other have said (Everything below return won't be executed) you should be careful with your while loops, they are infinite loops:
while ((Number - 365) >= 0) {
annee += 1; //this calculates the number of years
}
If Number - 365 >= 0 then you're inside the while and you're adding 1 to annee, and this will not stop the loop since Number - 365 >= 0 will continue to be satisfied.
Same thing with your second loop.
"return" exits the method. If you want to return all of them (years, months, days) you can use an array. Your code had generally many mistakes, and similar operations were done on nombre (or Number as you had it) multiple times. I have tried to make to code runnable.
public double[] Convertir(double nombre) {
double[] yearsWeeksAndDays = new double[3];
double annee = 0;
double semaine = 0;
while (nombre >= 365) {
annee += 1; //this calculates the number of years
nombre -= 365;
}
yearsWeeksAndDays[0] = annee;
while (nombre >= 7) {
semaine = semaine + 1;
nombre -= 7;
}//this calculates the number of weeks
yearsWeeksAndDays[1] = semaine;
yearsWeeksAndDays[2] = nombre;
return yearsWeeksAndDays;
}
You need to wrap you 3 return values into a class and return that. Something like this ought to work:
public static void main(String[] args) {
System.out.println(convertir(365));
System.out.println(convertir(366.5));
System.out.println(convertir(456));
}
static class Duration {
int years;
int weeks;
double days;
#Override
public String toString() {
return years + " years, " + weeks + " weeks and " + days + " days.";
}
}
public static Duration convertir(double total) {
final Duration duration = new Duration();
duration.years = (int) (total / 365);
total = total % 365;
duration.weeks = (int) (total / 7);
total = total % 7;
duration.days = total;
return duration;
}
Output:
1 years, 0 weeks and 0.0 days.
1 years, 0 weeks and 1.5 days.
1 years, 13 weeks and 0.0 days.
Obviously it needs a little translation but French isn't my strong suit.
its throwing unrreachable code because compiler knows that when the controll reaches that return statement, then it would return and no more code would be executed.To solve this, what you could do is, either put the return statement in a condition block like i have shown below, but again this program wont return u the result you wanted. it will return only the year. if you want the entire result ie. number of years + number of weeks + number of days i would suggest you to make the entire answer to a single string and return.
public double Convertir(double Number) {
// Number = nombre;
double annee = 0;
double semaine = 0;
double jour = 0;
while ((Number - 365) >= 0) {
annee += 1; // this calculates the number of years
}
if (annee > 0) {
return annee;
}
double nombreSemaine = Number - (annee * 365);
while ((nombreSemaine - 7) >= 0) {
semaine = semaine + 1;
}// this calculates the number of weeks
if (semaine > 0)
return semaine;
double nombreJour = Number - (annee * 365) - (semaine * 7);
nombreJour = jour;
return jour;
}

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