Simplifying splitting seconds into years, days, etc - java

I have to code a program which calculates seconds into years, days, hours, minutes, seconds.
My code so far:
public static void main(String[] args) {
long s = IOTools.readLong("Give seconds:");
long a = s / 31536000;
long t = (s % 3153600) / 86400;
long h = ((s % 3153600) % 86400) / 3600;
long m = (((s % 3153600) % 86400) % 3600) / 60;
long r = (((s % 3153600) % 86400) % 3600) % 60;
System.out.println( a + " year(s) " + t + " day(s) " + h + " hour(s) " + m + " minute(s) " + r + " second(s)!");
}
I want to make it simpler, for example with an if-else condition. Something like: divide the seconds by 31536000, save it in a. When there is a remainder, do this, and so on. But I have no idea how to start.
Also I have problems to typecast. I don't want to use long all the time, as it is not necessary anymore when the program calculates the days.

I think the Calendar class here can be pretty handy and you'll avoid complicated calculations. After you read the seconds from the input, you'll just have to convert them into milliseconds and pass the result to a Calendar instance.
Then, you can fetch the day, month, year like this:
long s = IOTools.readLong("Give seconds:");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(s * 1000);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY);

As you suggest you can use the remainder after each step:
long s = IOTools.readLong("Give seconds:");
long a = s / 31536000;
s %= 31536000;
long t = s / 86400;
s %= 86400;
long h = s / 3600;
s %= 3600;
long m = s / 60;
long r = s % 60;

BigDecimal input = new BigDecimal("your input");
long longVal = input.longValue();
int hours = (int) longVal / 3600;
int remainder = (int) longVal - hours * 3600;
int mins = remainder / 60;
remainder = remainder - mins * 60;
int secs = remainder;
System.out.println("hours: "+hours);
System.out.println("Mins: "+mins);
System.out.println("Sec: "+secs)

Related

How to calculate the difference in minutes between two timeStamp ( with different days)?

I'm trying to calculate a difference in minutes between two java TimeStamps when I write:
Timestamp t1,t2;
t2.getTime()-t1.getTime();
it returns only the difference between the two times and
I need the difference the whole times (including days)
Try this
long difftime = t1.getTime() - t2.getTime();
long seconds = diff / 1000;
long minutes = seconds / 60;
long hours = minutes / 60;
long days = hours / 24;
Difference between 2 timestamps gives milliseconds. Apply Maths afterwards:
// get time difference in seconds
long milliseconds = timestamp2.getTime() - timestamp1.getTime();
int seconds = (int) milliseconds / 1000;
// calculate hours minutes and seconds
int hours = seconds / 3600;
int minutes = (seconds % 3600) / 60;
seconds = (seconds % 3600) % 60;
Assuming you mean java.sql.Timestamp, the code below seems to work just fine:
import java.sql.Timestamp;
class Scratch {
public static final long MINUTES_PER_HOUR = 60;
public static final long SECONDS_PER_MINUTE = 60;
public static final long HOURS_PER_DAY = 24;
public static final long MILLIS_PER_SECOND = 1000L;
public static void main(String[] args) {
long oneDayPlusFiveMinutesInMillis = (MILLIS_PER_SECOND * SECONDS_PER_MINUTE) * ( 5 + MINUTES_PER_HOUR * HOURS_PER_DAY);
Timestamp t0 = new Timestamp(System.currentTimeMillis());
Timestamp t1 = new Timestamp(t0.getTime() + oneDayPlusFiveMinutesInMillis);
long diff = (t1.getTime() - t0.getTime()) / (MILLIS_PER_SECOND * SECONDS_PER_MINUTE);
System.out.println("t1 - t0 = " + diff + " minutes");
}
}
Returns:
t1 - t0 = 1445 minutes
Timestamp t1 = new Timestamp(new Date("04/26/2019 20:32:49").getTime());
Timestamp t2 = new Timestamp(new Date("04/27/2019 19:32:49").getTime());
long diff = t2.getTime() - t1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
long diffTotMinutes = diff / (60 * 1000);
System.out.println("Days: " + diffDays + " \nTime: " + diffHours + ":" + diffMinutes + ":" + diffSeconds);
System.out.println("Total Minutes: " + diffTotMinutes);
Out Put:
Days: 0
Time: 23:0:0
Total Minutes: 1380

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

Why does this time unit conversion return zeroes?

I am experiencing a problem with the code below. It's converting milliseconds to months, days, hours, and minutes.
long diffms = date2l - date1l; //The result here is in milliseconds; The value of date2l - date1l are different
long diff_minute = diffms / 60000;
long diff_hour = diff_minute / 60; float diff_minute_now = (diff_minute % 1) * 60; int dmn = (int) diff_minute_now;
long diff_day = diff_hour / 24; float diff_hour_now = (diff_hour % 1) * 24; int dhn = (int) diff_hour_now;
long diff_month = diff_day / 30; float diff_day_now = (diff_day % 1) * 30; int ddn = (int) diff_day_now;
diffe = new LabelField
("Remaining Time : " + Long.toString(diff_month) + " month(s) "
+ Integer.toString(ddn) + " day(s) "
+ Integer.toString(dhn) + " hour(s) "
+ Integer.toString(dmn) + " minute(s)");
add(diffe);
Why are the result values all zeroes?
EDIT:
#BicycleDude I modify your code into:
long diffms = date2l - date1l;
long ts = diffms / 1000;
long mo = ts / 60 / 60 / 24 / 30;
long d = (ts - mo * 30 * 24 * 60 * 60) / (60 * 60 * 24);
long h = (ts - d * 24 * 60 * 60) / (60 * 60);
long m = (ts - h * 60 * 60) / 60;
But the hours doesn't work
'anything % 1' will return 0. it's probably not what you intended.
The variables you divide initially are type long. So their results will also be long. (e.g. 12345 / 100 = 123 not 123.45).
The modulo operator works on remainder on division of integers. (e.g. 12345 % 100 = 45).
The algorithm you supplied doesn't extract day, month, hour, minute, second in the manner you expected. It requires rework before it's correct.
I've reworked the formulas with the assumption there are 31 days in a month:
long diffms = date2l - date1l;
long mo = (diffms / 1000 / 60 / 60 / 24 / 31);
long d = (diffms / 1000 / 60 / 60 / 24) % 31;
long h = (diffms / 1000 / 60 / 60) % 24;
long m = (diffms / 1000 / 60) % 60;
long s = (diffms / 1000) % 60;
I'm going to base my answer on the edited part of the code, since BicycleDude has already pointed out what was wrong with the modulo operations.
long diffms = date2l - date1l; //difference in ms
long ts = diffms / 1000; //total difference in seconds
long mo = ts / 60 / 60 / 24 / 30; //(1)
long d = (ts - mo * 30 * 24 * 60 * 60) / (60 * 60 * 24); //follows on because of (1)
long h = (ts - d * 24 * 60 * 60) / (60 * 60); //follows on because of (1)
long m = (ts - h * 60 * 60) / 60; //follows on because of (1)
Alright, I thought there would be multiple problems, but I think (think, I'm probably missing something...) that the main error is coming from your calculation of months, which I denoted in the code by the comment (1). You can't calculate the difference in months like that.
Why? What about if there was more than one month in differences? Wouldn't you need to divide by 31, instead? Or if it was a leap year? You'd need to divide by 29 if it was February. Since integer division doesn't round or account for decimals, you can get inaccuracies in your difference-in-months calculation. It's probably best if you instead use the differences in hours to calculate the difference in days, and from there you can figure out the difference in months. (Edit: I think you'd also need to take into account the factors I mentioned above when calculating the difference in months from the difference in days, by checking what your "origin" and "target" dates are, though I wouldn't be too sure of writing it myself at thie stage...)
Since you have a problem with the way you calculate the difference in months, and you use the erroneous value to calculate the difference in days, I think this results in the error propagating down to some of your other values (eg. the difference in hours).
EDIT
Okay, I mucked around with the code a bit more. As I noted earlier, your months calculation was dangerous and affected your days calculation, which potentially introduced errors later on.
With the example you provided in the comments, your code had a discrepancy of 3 days in the number of days. (The example was 19 January 2012 to 3 May 2012). I ran this against BicycleDude's code and it was fine.
I'll repost the code, and I've just added one line to find the number of days, based on how many hours have passed.
long h = ts / 60 / 60; // hour part
long m = (ts - h * 60 * 60) / 60; // minute part
long s = (ts - h * 60 * 60 - m * 60); // second part
long d = h / 24;
If you like to make it so that you can read that "there are w days, x hours, y minutes and z seconds between date2l and date1l", you could do something like this:
long date2l = Timestamp.valueOf("2012-05-03 05:30:10").getTime();
long date1l = Timestamp.valueOf("2012-01-19 00:00:00").getTime();
long diffms = date2l - date1l; //difference in ms
long diff_seconds = diffms / 1000; //total difference in seconds
long diff_mins = diff_seconds / 60; //total difference in minutes
long diff_hours = diff_mins / 60; //total difference in hours
long diff_days = diff_hours / 24; //total difference in days
long x = (diff_seconds - diff_days * 60 * 60 * 24) / (60 * 60);
long y = ((diff_seconds - (diff_hours * 60 * 60))) / 60;
long z = ((diff_seconds - (diff_mins * 60)));
long w = diff_days;
System.out.println(w + " " + x + " " + y + " " + z);
And it appears to work.
I haven't figured out the months part because that's a lot more non-trivial, but yeah. This kinda works?
The TimeUnit class provides factory methods that simplifies most of your work:
import static java.util.concurrent.TimeUnit.*;
// First, calculate the total difference in each unit
long diffDays = MILLISECONDS.toDays(diffMs);
long diffHours = MILLISECONDS.toHours(diffMs);
long diffMinutes = MILLISECONDS.toMinutes(diffMs);
long diffSeconds = MILLISECONDS.toSeconds(diffMs);
// Next, calculate the differences
long months = diffDays / 30;
long days = diffDays - 30 * months;
long hours = diffHours - DAYS.toHours(diffDays);
long minutes = diffMinutes - HOURS.toMinutes(diffHours);
long seconds = diffSeconds - MINUTES.toSeconds(diffMinutes);

Java dates difference in milliseconds

I've written the following code, but I always just get...
4838399999
Seconds is : 59
Minutes is : 59
Hours is : 23
Days is : 7
Calendar xmas = Calendar.getInstance();
final Calendar now = Calendar.getInstance();
xmas.set(Calendar.YEAR, 2011);
xmas.set(Calendar.MONTH, Calendar.DECEMBER);
xmas.set(Calendar.DAY_OF_MONTH, 25);
long milliseconds1 = now.getTimeInMillis();
long milliseconds2 = xmas.getTimeInMillis();
long diff = milliseconds2 - milliseconds1;
System.out.println(diff);
diff = diff / 1000;
final long diffSeconds = diff % 60;
System.out.println("Seconds is : " + diffSeconds);
diff = diff / 60;
final long diffMinutes = diff % 60;
System.out.println("Minutes is : " + diffMinutes);
diff = diff / 60;
final long diffHours = diff % 60;
System.out.println("Hours is : " + diffHours);
diff = diff / 24;
final long diffDays = diff % 24;
System.out.println("Days is : " + diffDays);
Can anyone see anything wrong with this logic to find the days, hours, minutes and seconds till xmas?
When you do:
diff = diff / 1000;
you're permanently losing the remainder. It should be something like:
long seconds = diff / 1000; // seconds is milliseconds / 1000
long milliseconds = diff % 1000; // remainder is milliseconds that are not composing seconds.
long minutes = seconds / 60;
seconds = seconds % 60;
long hours = minutes / 60;
minutes = minutes % 60;
The same pattern of the last four continues.
These two lines are wrong:
final long diffHours = diff % 60
final long diffDays = diff % 24;
Also, you're not setting the hours/minutes/seconds/milliseconds on xmas, so it gets the hours, minutes, and seconds from the current time. For example, if you run the program at 4:30:20 AM, then it will give you the time until 4:30:20 AM on Christmas. You probably want the time until 00:00:00 on Christmas.

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