converting seconds to hours,minutes, and seconds? - java

so Im trying to make a program that can convert s from input into h, m and s. my code so far looks like this:
import java.util.Scanner;
class q2_5{
public static void main(String args[]){
Scanner input = new Scanner(System.in);
int s=0;//seconds
int m=0;//minutes
int h=0;//hour
System.out.println("how many seconds?");
s=input.nextInt();
if(s >= 60){
m=s/60;
} if(m>=60){
h=m/60;
}
System.out.println(s + "s = " + h + " h " + m + " m " + s + "s ");
}
}
ok so I had to initialize s,m,h to 0 cuz if not I was getting problems in the if statement, so I just put it to 0, since I can change it later :) ok. so the problem with this program right now is that if I type in 3603 I get this output: 3603s = 1 h 60 m 3603s, if I type in 3600 I get this:
3600s = 1 h 60 m 3600s, but the output should have been 3603s = 1h 0m 3s and 3600s = 1h 0m 0s respectively. any tips/advice/solutions on how to solve this problem? :D thanks in advance!

My solution is:
String secToTime(int sec) {
int second = sec % 60;
int minute = sec / 60;
if (minute >= 60) {
int hour = minute / 60;
minute %= 60;
return hour + ":" + (minute < 10 ? "0" + minute : minute) + ":" + (second < 10 ? "0" + second : second);
}
return minute + ":" + (second < 10 ? "0" + second : second);
}

Obviously you are doing some homework/practice to learn Java. But FYI, in real work you needn't do those calculations and manipulations. There’s a class for that.
java.time.Duration
For a span of time, use the Duration class. No need for you to do the math.
Duration d = Duration.ofSeconds( s );
The standard ISO 8601 format for a string representing a span of time unattached to the timeline is close to your desired output: PnYnMnDTnHnMnS where the P marks the beginning and the T separates any years-months-days from any hours-minutes-seconds. So an hour and a half is PT1H30M.
The java.time classes use the ISO 8601 formats by default when parsing or generating strings.
String output = d.toString() ;
In Java 9 and later, you can call the to…Part methods to retrieve the individual parts of hours, minutes, and seconds.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 brought some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android (26+) bundle implementations of the java.time classes.
For earlier Android (<26), the process of API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….

Java 8 brings a great API for date and time manipulation.
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
public class Converter {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
public String convert(int seconds) {
LocalTime time = LocalTime.MIN.plusSeconds(seconds).toLocalTime();
return formatter.format(time);
}
}
Basically, this code adds the number of number of seconds to the minimum datetime supported, which, naturally, has HH:mm:ss equals to 00:00:00.
As your are interested in the time only, you extract it by calling toLocalTime() and format it as wanted.

You can do it all in a single line:
System.out.println((s/3600) + ' hours ' + ((s/60)%60) + ' minutes ' + (s%60) + ' seconds');

You never changed the value of s. A quick work around would be s = s - (h*3600 + m*60)
EDIT: t = s - (h*3600 + m*60)

Try subtracting from the first term every time you set a lower term.
class Test{
public static void main(String args[]){
Scanner input = new Scanner(System.in);
int s=0;//seconds
int m=0;//minutes
int h=0;//hour
System.out.println("how many seconds?");
s=input.nextInt();
if(s >= 60){
m=s/60;
s = s- m*60;
} if(m>=60){
h=m/60;
m = m - h*60;
}
System.out.println(s + "s = " + h + " h " + m + " m " + s + "s ");
}
}
Just by the way, too, remember to close your input scanner! Like so : input.close() near the end of the program.

You should try this
import java.util.Scanner;
public class Time_converter {
public static void main(String[] args)
{
Scanner input = new Scanner (System.in);
int seconds;
int minutes ;
int hours;
System.out.print("Enter the number of seconds : ");
seconds = input.nextInt();
hours = seconds / 3600;
minutes = (seconds%3600)/60;
int seconds_output = (seconds% 3600)%60;
System.out.println("The time entered in hours,minutes and seconds is:");
System.out.println(hours + " hours :" + minutes + " minutes:" + seconds_output +" seconds");
}
}

import java.util.Scanner;
public class Prg2 {
public static void main(String[] args) {
int seconds = 0;
int hours = 0;
int minutes = 0;
int secondsDisp = 0;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of seconds: ");
seconds = in.nextInt();
hours = seconds/3600;
minutes = (seconds - (hours*3600))/60;
secondsDisp = ((seconds - (hours*3600)) - (minutes * 60));
System.out.println(seconds + " seconds equals " + hours + " hours, " + minutes + " minutes and " + secondsDisp + " seconds");
}
}

class time{
public static void main (String args[]){
int duration=1500;
String testDuration = "";
if(duration < 60){
testDuration = duration + " minutes";
}
else{
if((duration / 60)<24)
{
if((duration%60)==0){
testDuration = (duration / 60) + " hours";
}
else{
testDuration = (duration / 60) + " hours," + (duration%60) + " minutes";
}
}
else{
if((duration%60)==0){
if(((duration/60)%24)==0){
testDuration = ((duration / 24)/60) + " days,";
}
else{
testDuration = ((duration / 24)/60) + " days," + (duration/60)%24 +"hours";
}
}
else{
testDuration = ((duration / 24)/60) + " days," + (duration/60)%24 +"hours"+ (duration%60) + " minutes";
}
}
}
System.out.println(testDuration);
}
}

A simpler solution would be:
T = in.nextInt();
int s = T%60;
int minute = T/60;
int m = minute%60;
int h = minute/60;
return h+"h"+m+"m"+s+"s";

use this code:
import java.util.Scanner;
class q2_5{
public static void main(String args[]){
Scanner input = new Scanner(System.in);
int s=0;//seconds
int m=0;//minutes
int h=0;//hour
int s_input=0;
System.out.println("how many seconds?");
s_input=input.nextInt();
s=s_input%60;
if(s >= 60){
m=s_input/60;
}if(m>=60){
h=m/60;
m=m%60;
}
System.out.println(s + "s = " + h + " h " + m + " m " + s + "s ");
}
}

Related

Updating Date inside a while loop, Java

Im trying to compare the real world date with a user input date within a while loop. Although the initial execute is correct, the second time its executing the date stays the same. Ive tried asking for the date inside the while loop and now most recently from within a class method but still the date stays the same.
How can I retrieve an up to date date?
import java.util.Date;
import java.util.Scanner;
class Watch {
Date CurrentTimeAndDate = new Date();
int CurrentMinutes() {
int currentMinutes = CurrentTimeAndDate.getMinutes();
System.out.println(currentMinutes);
return currentMinutes;
}
}
public class App {
public static void main(String[] args) throws InterruptedException {
Scanner input = new Scanner(System.in);
String timer = null;
int i = 0;
int num = 0;
Date TimeAndDate = new Date();
int getDay = TimeAndDate.getDay();
int getMonth = TimeAndDate.getMonth() + 1;
int getYear = TimeAndDate.getYear() + 1900;
int getMinutes = TimeAndDate.getMinutes();
Watch watch1 = new Watch();
String[] Month = { "", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
String[] Day = { "", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" };
System.out.println("Current time and date is " + TimeAndDate);
System.out.println("Printing my way! " + Day[getDay] + " " + Month[getMonth] + " " + getYear + " " + getMinutes);
System.out.println(" Enter a short description of what you want reminding about ");
String rem = input.nextLine();
System.out.println(" Enter date of reminder 1-7");
while (i < 7) {
System.out.println(i + 1 + " = " + Day[i + 1]);
i++;
}
int day = input.nextInt();
System.out.println("Enter Month of reminder");
i = 0;
while (i < 12) {
System.out.println(i + 1 + " " + "=" + " " + Month[i + 1]);
i++;
}
int month = input.nextInt();
System.out.println("Enter year");
int year = input.nextInt();
System.out.println("Enter Minutes, for testing purposes");
int userInputMinutes = input.nextInt();
System.out.println("Date set to remind you about " + rem + " " + Day[day] + " " + Month[month] + " " + year);
if (year > getYear) {
System.out.println("Its time to remind you about ");
} else {
System.out.println("Waiting");
}
int Mins = 0;
while (userInputMinutes != Mins) {
Mins = watch1.CurrentMinutes();
System.out.println("Current Minutes = " + getMinutes);
System.out.println("Entered minutes =" + userInputMinutes);
Thread.sleep(10000);
}
System.out.println("Its time to remind you about " + rem);
}
public static void Date(String time) {
}
}
You are setting the new Date() only once. So you will be getting that same in while loop iterations. To get a new date for every iteration, you have to set the below code inside the while loop
TimeAndDate = new Date();
int getDay = TimeAndDate.getDay();
int getMonth = TimeAndDate.getMonth() + 1;
int getYear = TimeAndDate.getYear() + 1900;
int getMinutes = TimeAndDate.getMinutes();
Watch watch1 = new Watch();
* Note: Date is a deprecated class. Please refer #Ole V.V. answer for
the correct class to use.*
First, use java.time, the modern Java date and time API, for you date and time work. Always. The Date class that you used (misused, really, I’ll get back to that) is poorly designed and long outdated. Never use that.
Getting current minutes
To get the current minute of the hour:
int currentMinutes() {
return LocalTime.now(ZoneId.systemDefault()).getMinute();
}
To read day of week or month from the user
Also use java.time for days of the week and for months. Your code is reinventing wheels. You should prefer to use library classes and methods that are already there for you. For example:
System.out.println(" Enter day of week of reminder 1-7");
for (DayOfWeek dow : DayOfWeek.values()) {
System.out.println("" + dow.getValue() + " = " + dow
.getDisplayName(TextStyle.SHORT_STANDALONE, Locale.ENGLISH));
}
int day = input.nextInt();
DayOfWeek dow = DayOfWeek.of(day);
System.out.println("You have chosen " + dow);
Example interaction:
Enter day of week of reminder 1-7
1 = Mon
2 = Tue
3 = Wed
4 = Thu
5 = Fri
6 = Sat
7 = Sun
2
You have chosen TUESDAY
Most methods of the Date class are deprecated for a reason
As I said, Date is poorly designed and long outdated. More than that, most of the constructors and methods of the class were deprecated in Java 1.1 in February 1997 because they work unreliably across time zones. So even if you insisted on using Date (which I hope you don’t), you should still stay far away from the deprecated methods including all of the get methods except getTime (which converts to milliseconds since the epoch).
Link
Oracle tutorial: Date Time explaining how to use java.time.

How do I get the military time difference to read correctly?

I am trying to write a program in which the console tells a person the difference between two times WITHOUT IF STATEMENTS, in "military time" or 24 hr time. So far, I have:
import java.util.Scanner;
public class MilTimeDiff {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter the first time: ");
String time1 = s.next();
System.out.print("Enter the second time: ");
String time2 = s.next();
String tm1 = String.format("%02d", Integer.parseInt(time1));
String tm2 = String.format("%02d", Integer.parseInt(time2));
int t1 = Integer.parseInt(tm1);
int t2 = Integer.parseInt(tm2);
int difference = t2 - t1;
while (t1 < t2) {
String tmDif = Integer.toString(difference);
System.out.println("The difference between times is " + tmDif.substring(0, 1) + " hours " +
tmDif.substring(1) + " minutes.");
break;
}
}
}
But I have two issues: one: if I make time one 0800, and time two 1700, it gives me the correct 9 hours. But if the difference is 10 hours or more, it gives 1 hour and a lot of minutes. I thought using the String.format method would help, but it doesn't do anything.
two: I'm not sure how to approach a situation where time 1 is later than time 2.
Thanks!
You can try below code which will give Time difference in military format :
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter the first time: ");
String time1 = s.next();
System.out.print("Enter the second time: ");
String time2 = s.next();
String tm1 = String.format("%02d", Integer.parseInt(time1));
String tm2 = String.format("%02d", Integer.parseInt(time2));
String hrs1 = time1.substring(0, 2);
String min1 = time1.substring(2, 4);
String hrs2 = time2.substring(0, 2);
String min2 = time2.substring(2, 4);
// int difference = t2 - t1;
if (Integer.parseInt(time1) < Integer.parseInt(time2)) {
int minDiff = Integer.parseInt(min2) - Integer.parseInt(min1);
int hrsDiff = Integer.parseInt(hrs2) - Integer.parseInt(hrs1);
if (minDiff < 0) {
minDiff += 60;
hrsDiff--;
}
System.out.println("The difference between times is " + hrsDiff + " hours " + minDiff + " minutes.");
} else {
int minDiff = Integer.parseInt(min1) - Integer.parseInt(min2);
int hrsDiff = Integer.parseInt(hrs1) - Integer.parseInt(hrs2);
if (minDiff < 0) {
minDiff += 60;
hrsDiff--;
}
System.out.println("The difference between times is " + hrsDiff + " hours " + minDiff + " minutes.");
}
}

Time conversion in eclipse, having trouble [duplicate]

This question already has answers here:
How to format a number 0..9 to display with 2 digits (it's NOT a date)
(7 answers)
Closed 6 years ago.
package timeConversion;
import java.util.Scanner;
public class TimeConversion {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter the time in minutes: ");
int time = input.nextInt();//time in minutes
int hour = time / 60;// hour
int minute = time % 60; //minutes
System.out.print("The time is: " + hour + ":" + minute);
}
}
So I'm having trouble with values in the minute spot being less than 10. for example, when you time in 184 minutes, the output is 3:4, but i would like it to read 3:04. how could I go about doing this ?
Just a quick hack
if(minute < 10)
System.out.println("The time is: " + hour + ":0" + minute);
else
System.out.print("The time is: " + hour + ":" + minute);

Problems with a converter from seconds to day, hours, minutes, and seconds using Java

I am doing this for a programming class and I keep getting these errors when I go to compile the program in jGrasp:
TimeCalculator.java:94: error: variable dblMinutes might not have been initialized
+ timeFormat.format(dblMinutes) + " minutes, and " + timeFormat.format(dblSecondsAfterMinutes) + " seconds.");
^
TimeCalculator.java:94: error: variable dblSecondsAfterMinutes might not have been initialized
+ timeFormat.format(dblMinutes) + " minutes, and " + timeFormat.format(dblSecondsAfterMinutes) + " seconds.");
^
TimeCalculator.java:98: error: variable dblMinutes might not have been initialized
JOptionPane.showMessageDialog(null, "There are " + timeFormat.format(dblHours) + " hours, " + timeFormat.format(dblMinutes) + " minutes, and "
^
TimeCalculator.java:99: error: variable dblSecondsAfterMinutes might not have been initialized
+ timeFormat.format(dblSecondsAfterMinutes) + " seconds.");
^
TimeCalculator.java:101: error: variable dblMinutes might not have been initialized
else if (dblMinutes >= 1)
^
TimeCalculator.java:102: error: variable dblSecondsAfterMinutes might not have been initialized
JOptionPane.showMessageDialog(null, "There are " + timeFormat.format(dblMinutes) + " minutes and " + timeFormat.format(dblSecondsAfterMinutes) + " seconds.");
^
6 errors
My program is supposed to take user input (an amount in seconds) and convert it to days, hours, minutes, and seconds. It then should display the final amount.
Here is my code so far:
/*
This program prompts the user to enter an amount of seconds.
When the user enters an amount, it is stored in a variable and
calculated to how many days, hours, minutes, and seconds there
are in the given amount of seconds. The information is then
output for the user to read.
60 seconds = 1 minute
3600 seconds = 1 hour
86400 seconds = 1 day
*/
import javax.swing.JOptionPane;
import java.text.DecimalFormat;
public class TimeCalculator
{
public static void main(String[] args)
{
DecimalFormat timeFormat = new DecimalFormat("#0.#");//used for formatting output
//declaring needed variables
String strStartingSeconds;
double dblStartingSeconds, dblMinutes, dblHours, dblDays, dblSecondsAfterDays, dblSecondsAfterHours, dblSecondsAfterMinutes;
//get input from user for amount of seconds
strStartingSeconds = JOptionPane.showInputDialog("Enter the amount of seconds: ");
//convert input to a double
dblStartingSeconds = Double.parseDouble(strStartingSeconds);
if (dblStartingSeconds >= 86400)//check to see if it is one day or more
{
dblDays = dblStartingSeconds / 86400;//find how many days
dblSecondsAfterDays = dblStartingSeconds % 86400;//calculate how many seconds are left by finding the remainder
if (dblSecondsAfterDays >= 3600)//check to see if there is one hour or more
{
dblHours = dblSecondsAfterDays / 3600;//find how many hours
dblSecondsAfterHours = dblSecondsAfterDays % 3600;//calculate how many seconds are left by finding the remainder
if (dblSecondsAfterHours >= 60)//Check to see if there is one or more minutes
{
dblMinutes = dblSecondsAfterHours / 60;//Calculate how many minutes
dblSecondsAfterMinutes = dblSecondsAfterHours % 60;//calculate how many seconds are left by finding the remainder
}
else
{
dblMinutes = 0;//If there wasn't enough seconds, assign minutes as 0
}
}
else
dblHours = 0;//If there wasn't enough hours, assign hours as 0
}
else
{
dblDays = 0;//assign days as 0 since there wasn't enough seconds
if (dblStartingSeconds >= 3600)//check to see if there is one hour or more
{
dblHours = dblStartingSeconds / 3600;//find how many hours
dblSecondsAfterHours = dblStartingSeconds % 3600;//calculate how many seconds are left by finding the remainder
if (dblSecondsAfterHours >= 60)//Check to see if there is one or more minutes
{
dblMinutes = dblSecondsAfterHours / 60;//Calculate how many minutes
dblSecondsAfterMinutes = dblSecondsAfterHours % 60;//calculate how many seconds are left by finding the remainder
}
else
{
dblMinutes = 0;//assign minutes as 0 since there wasn't enough seconds
}
}
else
{
dblHours = 0;//assign hours as 0 since there wasn't enough hours
if (dblStartingSeconds >= 60)//Check to see if there is one or more minutes
{
dblMinutes = dblStartingSeconds / 60;//Calculate how many minutes
dblSecondsAfterMinutes = dblStartingSeconds % 60;//calculate how many seconds are left by finding the remainder
}
else
{
dblMinutes = 0;//Assign minutes as 0 since there wasn't enough seconds
JOptionPane.showMessageDialog(null, "There are " + timeFormat.format(dblStartingSeconds) + " seconds.");//Displays how many seconds there was
}
}
}
//Display the correct amount of time based on whether or not there was enough seconds for days, hours, or minutes
if (dblDays >= 1)
{
JOptionPane.showMessageDialog(null, "There are " + timeFormat.format(dblDays) + " days, " + timeFormat.format(dblHours) + " hours, "
+ timeFormat.format(dblMinutes) + " minutes, and " + timeFormat.format(dblSecondsAfterMinutes) + " seconds.");
}
else if (dblHours >= 1)
{
JOptionPane.showMessageDialog(null, "There are " + timeFormat.format(dblHours) + " hours, " + timeFormat.format(dblMinutes) + " minutes, and "
+ timeFormat.format(dblSecondsAfterMinutes) + " seconds.");
}
else if (dblMinutes >= 1)
JOptionPane.showMessageDialog(null, "There are " + timeFormat.format(dblMinutes) + " minutes and " + timeFormat.format(dblSecondsAfterMinutes) + " seconds.");
else
JOptionPane.showMessageDialog(null, "There are " + timeFormat.format(dblStartingSeconds) + " seconds.");
System.exit(0);//close application
}
}
I have no joke, spent hours looking through this and can't find what I'm doing wrong! I'm pretty new to programming, so anything will help (I probably did something stupid and obvious to an expert programmer).
Thanks,
-Cashe
double dblMinutes = 0;
Read about initializing fields here: http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html
Aside from your initialization issue... java.util.concurrent.TimeUnit is your best friend when dealing with converting units of time.

Java: convert seconds into day, hour, minute and seconds using TimeUnit

I am using TimeStamp class to convert seconds into Day,Hours,Minutes,Seconds. I used following code
public static void calculateTime(long seconds) {
int day = (int)TimeUnit.SECONDS.toDays(seconds);
long hours = TimeUnit.SECONDS.toHours(seconds) - TimeUnit.SECONDS.toHours(TimeUnit.SECONDS.toDays(seconds));
long minute = TimeUnit.SECONDS.toMinutes(seconds) - TimeUnit.SECONDS.toMinutes(TimeUnit.SECONDS.toHours(seconds));
long second = TimeUnit.SECONDS.toSeconds(seconds) - TimeUnit.SECONDS.toSeconds(TimeUnit.SECONDS.toMinutes(seconds));
System.out.println("Day " + day + " Hour " + hours + " Minute " + minute + " Seconds " + second);
}
But I am not getting right result.
For example when I called this method as calculateTime(3600) it gives me the result as Day 0 Hour 1 Minute 60 Seconds 3540 instead of Day 0 Hour 1 Minute 0 Seconds 0.
What is the wrong with my logic? Please help me.
It should be like
int day = (int)TimeUnit.SECONDS.toDays(seconds);
long hours = TimeUnit.SECONDS.toHours(seconds) - (day *24);
long minute = TimeUnit.SECONDS.toMinutes(seconds) - (TimeUnit.SECONDS.toHours(seconds)* 60);
long second = TimeUnit.SECONDS.toSeconds(seconds) - (TimeUnit.SECONDS.toMinutes(seconds) *60);
EDIT
Explanation:
Day calculation is correct, it does not require explanation.
TimeUnit.SECONDS.toHours(seconds) will give you direct conversion from seconds to hours without consideration for days you have already calculated. Minus the hours for days you already got i.e, day*24. You now got remaining hours.
Same for minute and second. You need to minus the already got hour and minutes respectively.
You can do like this to only use TimeUnit:
public static void calculateTime(long seconds) {
int day = (int) TimeUnit.SECONDS.toDays(seconds);
long hours = TimeUnit.SECONDS.toHours(seconds) -
TimeUnit.DAYS.toHours(day);
long minute = TimeUnit.SECONDS.toMinutes(seconds) -
TimeUnit.DAYS.toMinutes(day) -
TimeUnit.HOURS.toMinutes(hours);
long second = TimeUnit.SECONDS.toSeconds(seconds) -
TimeUnit.DAYS.toSeconds(day) -
TimeUnit.HOURS.toSeconds(hours) -
TimeUnit.MINUTES.toSeconds(minute);
System.out.println("Day " + day + " Hour " + hours + " Minute " + minute + " Seconds " + second);
}
or the slightly shorter but maybe not as intuitive
public static void calculateTime(long seconds) {
int day = (int) TimeUnit.SECONDS.toDays(seconds);
long hours = TimeUnit.SECONDS.toHours(seconds) -
TimeUnit.DAYS.toHours(day);
long minute = TimeUnit.SECONDS.toMinutes(seconds) -
TimeUnit.HOURS.toMinutes(TimeUnit.SECONDS.toHours(seconds));
long second = TimeUnit.SECONDS.toSeconds(seconds) -
TimeUnit.MINUTES.toSeconds(TimeUnit.SECONDS.toMinutes(seconds));
System.out.println("Day " + day + " Hour " + hours + " Minute " + minute + " Seconds " + second);
}
Simple method:
public static void calculateTime(long seconds) {
long sec = seconds % 60;
long minutes = seconds % 3600 / 60;
long hours = seconds % 86400 / 3600;
long days = seconds / 86400;
System.out.println("Day " + days + " Hour " + hours + " Minute " + minutes + " Seconds " + sec);
}
Here is a code i created : (For 3600 seconds it shows "Days:0 Hours:1 Minutes:0 Seconds:0")
public class TimeConvert
{
public static void main(String[] args)
{
int fsec,d,h,m,s,temp=0,i;
fsec=3600;
//For Days
if(fsec>=86400)
{
temp=fsec/86400;
d=temp;
for(i=1;i<=temp;i++)
{
fsec-=86400;
}
}
else
{
d=0;
}
//For Hours
if(fsec>=3600)
{
temp=fsec/3600;
h=temp;
for(i=1;i<=temp;i++)
{
fsec-=3600;
}
}
else
{
h=0;
}
//For Minutes
if(fsec>=60)
{
temp=fsec/60;
m=temp;
for(i=1;i<=temp;i++)
{
fsec-=60;
}
}
else
{
m=0;
}
//For Seconds
if(fsec>=1)
{
s=fsec;
}
else
{
s=0;
}
System.out.println("Days:"+d+" Hours:"+h+" Minutes:"+m+" Seconds:"+s);
}
}
Hope it answers your question.
Late but helpful
get time in the format 00:00:00
/**
* The time in format.
*
* in The Format of 00:00:00
*/
public String getTimeInFormat(long _SECONDS)
{
if(TimeUnit.SECONDS.toHours(_SECONDS)>0)
{
return String.format("%02d:%02d:%02d",
TimeUnit.SECONDS.toHours(_SECONDS),
TimeUnit.SECONDS.toMinutes(_SECONDS) -
TimeUnit.HOURS.toMinutes(TimeUnit.SECONDS.toHours(_SECONDS)),
TimeUnit.SECONDS.toSeconds(_SECONDS) -
TimeUnit.MINUTES.toSeconds(TimeUnit.SECONDS.toMinutes(_SECONDS)));
}
else {
return String.format("%02d:%02d",
TimeUnit.SECONDS.toMinutes(_SECONDS) -
TimeUnit.HOURS.toMinutes(TimeUnit.SECONDS.toHours(_SECONDS)),
TimeUnit.SECONDS.toSeconds(_SECONDS) -
TimeUnit.MINUTES.toSeconds(TimeUnit.SECONDS.toMinutes(_SECONDS)));
}
}
Try this
public static void calculateTime(long seconds) {
int day = (int)TimeUnit.SECONDS.toDays(seconds);
long hours = TimeUnit.SECONDS.toHours(seconds) ;
long tempSec = seconds - (TimeUnit.HOURS.toSeconds(hours) );
System.out.println("after hours calculation "+ tempSec);
long minute = TimeUnit.SECONDS.toMinutes(tempSec);
if(tempSec > TimeUnit.MINUTES.toSeconds(minute)){
tempSec = tempSec - (TimeUnit.MINUTES.toSeconds(minute) );
}else{
tempSec = TimeUnit.MINUTES.toSeconds(minute) - tempSec;
}
System.out.println("after min calculation "+ tempSec);
long second = TimeUnit.SECONDS.toSeconds(tempSec) ;
System.out.println("Day " + day + " Hour " + hours + " Minute " + minute + " Seconds " + second);
}
This is my code:
public static String secondsToString(TimeUnit greatestUnit, long sourceDuration, TimeUnit sourceUnit) {
int ordinal = greatestUnit.ordinal();
if(ordinal<=sourceUnit.ordinal())
return String.format("%02d", sourceDuration);
final long greatestDuration = greatestUnit.convert(sourceDuration, sourceUnit);
final long rest = sourceDuration - sourceUnit.convert(greatestDuration, greatestUnit);
return String.format("%02d:", greatestDuration) + secondsToString(TimeUnit.values()[--ordinal], rest, sourceUnit);
}
or by loop
public static String secondsToStringByLoop(TimeUnit greatestUnit, long sourceDuration, TimeUnit sourceUnit) {
final StringBuffer sb = new StringBuffer();
int ordinal = greatestUnit.ordinal();
while(true){
if(ordinal<=sourceUnit.ordinal()) {
sb.append(String.format("%02d", sourceDuration));
break;
}
final long greatestDuration = greatestUnit.convert(sourceDuration, sourceUnit);
// if(greatestDuration>0 || sb.length()>0)
sb.append(String.format("%02d:", greatestDuration));
sourceDuration -= sourceUnit.convert(greatestDuration, greatestUnit);
greatestUnit = TimeUnit.values()[--ordinal];
};
return sb.toString();
}
usage example:
String str = secondsToString(TimeUnit.DAYS, 1000, TimeUnit.SECONDS);
function returns: "00:00:16:40" (days:hours:minutes:seconds)
str = UnitsConverter.secondsToString(TimeUnit.DAYS, 1000, TimeUnit.MINUTES);
returns: "00:16:40" (days:hours:minutes)
str = UnitsConverter.secondsToString(TimeUnit.MINUTES, 1000, TimeUnit.SECONDS);
returns: "16:40" (minutes:seconds)
public static void timeCalculator(){
Scanner input = new Scanner(System.in);
System.out.print("Enter length of time in seconds: ");
int n = input.nextInt();
int nDay = n/86400;
int nHours = (n%86400)/3600;
int nMin = ((n%86400)%3600) /60;
int nSec =(((n%86400)%3600)%60);
System.out.println();
System.out.print("That is "+ nDay+ " day(s),"+nHours+" hour(s), "+nMin+" minute(s), and "+nSec+" second(s). ");
}

Categories