Converting minutes to time of day in my Java program - java

I am writing a program to convert minutes into the time of day. How can I write this to keep the hours in standard time, the hour should never exceed 12.
import java.util.*;
public class MinutesConverter {
public static void main(String[] args) {
int minutes;
int hours;
Scanner input = new Scanner(System.in);
System.out.print("Enter minutes: ");
minutes = input.nextInt();
hours = minutes / 60;
minutes %= 60;
System.out.print(hours + ":" + minutes);
}
}

You can make a little change in code, where you are assigning value to hour
here is what i can suggest:
hour = ( minutes / 60 ) % 24;

Related

How can I add 15 minutes to time and handle overflow?

I have an exercise in which I need to input hours and minutes in 24 hour format and after that the program will show me the time after 15 minutes. It doesn't work when minutes overflow after 59 minutes. When I have for example the input:
15
59
My output is:
15:74
I know that after 59 minutes at a normal clock will be 16:14. How can I handle this case correctly?
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int hours = in.nextInt();
int minutes = in.nextInt();
if ( minutes == 59 ){
hours = hours + 1;
minutes = 00;
minutes = minutes + 14; //because I passed 1 minute
}
else{
minutes = minutes + 15;
}
System.out.printf("%d:%02d" , hours , minutes);
}
}
In Java, you don't need to program such basic things "by hand" like in C. Java provides a lot of APIs. For example the time API. See for example LocalTime with its method plusMinutes.
It's easy you should use Modulo operation like this :
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int hours = in.nextInt();
int minutes = in.nextInt();
minutes = minutes + 15;
hours += minutes / 60;
minutes = minutes % 60;
System.out.printf("%d:%02d", hours, minutes);
}
Do it as follows:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int hours = in.nextInt();
int minutes = in.nextInt();
minutes=minutes+15;
if (minutes > 59) {
hours++;
}
minutes = minutes % 60;
hours = hours % 24;
System.out.printf("%d:%02d", hours, minutes);
}
}
A sample run:
15
59
16:14
Another sample run:
23
59
0:14

Convert long to remaining time

I'm currently trying to convert a long to a remaining time. I have got a
long remaining = XXXX
The long are the milliseconds to a certain date. For example: 3,600,000 should result in int weeks = 0, days = 0, hours = 1, minutes = 0, seconds = 0
how can I convert this long so that I end up with 5 ints:
int weeks;
int days;
int hours;
int minutes;
int seconds;
Thank you in advance!
DirtyDev
First, I suggest defining the number of ms in a second, minute, hour, etc as constants
static final int SECOND = 1000; // no. of ms in a second
static final int MINUTE = SECOND * 60; // no. of ms in a minute
static final int HOUR = MINUTE * 60; // no. of ms in an hour
static final int DAY = HOUR * 24; // no. of ms in a day
static final int WEEK = DAY * 7; // no. of ms in a week
Then, you can use basic division (/) and modulus (%) operations to find what you need.
long remaining = XXXX;
int weeks = (int)( remaining / WEEK);
int days = (int)((remaining % WEEK) / DAY);
int hours = (int)((remaining % DAY) / HOUR);
int minutes = (int)((remaining % HOUR) / MINUTE);
int seconds = (int)((remaining % MINUTE) / SECOND);
Excuse me, I don’t want to criticize too much, still I gather from the other answers that it’s easy to either write code that is hard to read or code with typos that gives an incorrect result. DirtyDev, I am aware that you may not be allowed to use Duration, but for anyone else:
long remaining = 3_600_000;
Duration remainingTime = Duration.ofMillis(remaining);
long days = remainingTime.toDays();
remainingTime = remainingTime.minusDays(days);
long weeks = days / 7;
days %= 7; // or if you prefer, days = days % 7;
long hours = remainingTime.toHours();
remainingTime = remainingTime.minusHours(hours);
long minutes = remainingTime.toMinutes();
remainingTime = remainingTime.minusMinutes(minutes);
long seconds = remainingTime.getSeconds();
System.out.println("" + weeks + " weeks " + days + " days "
+ hours + " hours " + minutes + " minutes " + seconds + " seconds");
This prints:
0 weeks 0 days 1 hours 0 minutes 0 seconds
It’s not perfect, but I believe it’s both readable, correct and robust. Duration was meant for times from hours down to nanoseconds, so we still have to do the weeks “by hand”.
Happy New Year.
This should do what you want.
long inputTimeInMilliseconds = 93800000;
long milliseconds = inputTimeInMilliseconds % 1000;
long seconds = (inputTimeInMilliseconds / 1000) % 60 ;
long minutes = ((inputTimeInMilliseconds / (1000*60)) % 60);
long hours = ((inputTimeInMilliseconds / (1000*60*60)) % 24);
long days = ((inputTimeInMilliseconds / (1000*60*60*24)) % 7);
long weeks = (inputTimeInMilliseconds / (1000*60*60*24*7));
String remainingTime = "time:"+weeks+":"+days+":"+ hours+":"+minutes+":"+seconds+":"+milliseconds;
System.out.println(remainingTime);

for-loop time conversion using java

I'm just new in java.I am trying to convert money to time which is 1 dollar == 3 minutes but minutes-- wont let me display the exact minutes of time in the second loop
package javaapplication8;
import java.util.Scanner;
public class JavaApplication8 {
public static void main(String[] args) {
/*
1 Dollar = 3 minutes
*/
//I am trying to convert money to time which is 1 dollar == 3 minutes but minutes--
//wont let me display the exact minutes of time in the second loop
int minutes;
int amount;
int hour=0;
int time;
Scanner in = new Scanner(System.in);
System.out.println("Please Enter Amount");
amount = in.nextInt();
time = amount * 3;
for (minutes = time; minutes>=59; minutes--)
{
minutes = minutes- 59;
hour = hour+1;
System.out.println(minutes+"minutes");
System.out.println(hour+"hour");
}
}
}
So if money == 40 here is the problem:
Please enter amount:
40
61 minutes
1 hour
here lies the problem it should be 2 minutes but because of minutes-- its not,
1 minutes
2 hour
Your second loop is a weird way of implementing it you should replace minute-- by minute-=60 like so:
for (minutes = time; minutes>=60; minutes-=60) {
hour = hour+1;
}
but you could just implement it by using arithmetic:
hour = minute/60;
minute = minute % 60;

JAVA convert minutes into default time [hh:mm:ss]

what is the easiest and fastest way to convert minutes (double) to default time hh:mm:ss
for example I used this code in python and it's working
time = timedelta(minutes=250.0)
print time
result:
4:10:00
is there a java library or a simple code can do it?
EDIT: To show the seconds as SS you can make an easy custom formatter variable to pass to the String.format() method
EDIT: Added logic to add one minute and recalculate seconds if the initial double value has the number value after the decimal separator greater than 59.
EDIT: Noticed loss of precision when doing math on the double (joy of working with doubles!) seconds, so every now and again it would not be the correct value. Changed code to properly calculate and round it. Also added logic to treat cases when minutes and hour overflow because of cascading from seconds.
Try this (no external libraries needed)
public static void main(String[] args) {
final double t = 1304.00d;
if (t > 1440.00d) //possible loss of precision again
return;
int hours = (int)t / 60;
int minutes = (int)t % 60;
BigDecimal secondsPrecision = new BigDecimal((t - Math.floor(t)) * 100).setScale(2, RoundingMode.HALF_UP);
int seconds = secondsPrecision.intValue();
boolean nextDay = false;
if (seconds > 59) {
minutes++; //increment minutes by one
seconds = seconds - 60; //recalculate seconds
}
if (minutes > 59) {
hours++;
minutes = minutes - 60;
}
//next day
if (hours > 23) {
hours = hours - 24;
nextDay = true;
}
//if seconds >=10 use the same format as before else pad one zero before the seconds
final String myFormat = seconds >= 10 ? "%d:%02d:%d" : "%d:%02d:0%d";
final String time = String.format(myFormat, hours, minutes, seconds);
System.out.print(time);
System.out.println(" " + (nextDay ? "The next day" : "Current day"));
}
Of course this can go on and on, expanding on this algorithm to generalize it. So far it will work until the next day but no further, so we could limit the initial double to that value.
if (t > 1440.00d)
return;
Using Joda you can do something like:
import org.joda.time.Period;
import org.joda.time.format.PeriodFormatter;
import org.joda.time.format.PeriodFormatterBuilder;
final Period a = Period.seconds(25635);
final PeriodFormatter hoursMinutes = new PeriodFormatterBuilder().appendHours().appendSuffix(" hour", " hours")
.appendSeparator(" and ").appendMinutes().appendSuffix(" minute", " minutes").appendSeparator(" and ")
.appendSeconds().appendSuffix(" second", " seconds").toFormatter();
System.out.println(hoursMinutes.print(a.normalizedStandard()));
//Accept minutes from user and return time in HH:MM:SS format
private String convertTime(long time)
{
String finalTime = "";
long hour = (time%(24*60)) / 60;
long minutes = (time%(24*60)) % 60;
long seconds = time / (24*3600);
finalTime = String.format("%02d:%02d:%02d",
TimeUnit.HOURS.toHours(hour) ,
TimeUnit.MINUTES.toMinutes(minutes),
TimeUnit.SECONDS.toSeconds(seconds));
return finalTime;
}

Java: convert seconds to minutes, hours and days [duplicate]

This question already has answers here:
Convert seconds value to hours minutes seconds?
(22 answers)
Closed 6 years ago.
The task is:
The output should look like this (it is a good idea to echo back the input): You entered 500,000 seconds, which is 5 days, 18 hours, 53 minutes and 20 seconds. (5 days 18:53:20 hours)
How should I do it? What is the easiest way to understand and do it?
Also the instructor said "no hard coding" which I'm not exactly sure what is, but I think he wants us to assign them constants.
An example using the built-in TimeUnit.
long uptime = System.currentTimeMillis();
long days = TimeUnit.MILLISECONDS
.toDays(uptime);
uptime -= TimeUnit.DAYS.toMillis(days);
long hours = TimeUnit.MILLISECONDS
.toHours(uptime);
uptime -= TimeUnit.HOURS.toMillis(hours);
long minutes = TimeUnit.MILLISECONDS
.toMinutes(uptime);
uptime -= TimeUnit.MINUTES.toMillis(minutes);
long seconds = TimeUnit.MILLISECONDS
.toSeconds(uptime);
With basic Java arithmetic calculations:
First consider the following values:
1 minute = 60 seconds
1 hour = 3600 seconds (60 * 60)
1 day = 86400 second (24 * 3600)
First divide the input by 86400. If you you can get a number greater than 0, this is the number of days.
Again divide the remained number you get from the first calculation by 3600. This will give you the number of hours.
Then divide the remainder of your second calculation by 60 which is the number of minutes
Finally the remained number from your third calculation is the number of seconds
The code snippet is as follows:
int input = 500000;
int numberOfDays;
int numberOfHours;
int numberOfMinutes;
int numberOfSeconds;
numberOfDays = input / 86400;
numberOfHours = (input % 86400) / 3600 ;
numberOfMinutes = ((input % 86400) % 3600) / 60
numberOfSeconds = ((input % 86400) % 3600) % 60;
It should be like:
public static void calculateTime(long seconds) {
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);
System.out.println(
"Day " + day + " Hour " + hours + " Minute " + minute +
" Seconds " + second);
}
Explanation:
TimeUnit.SECONDS.toHours(seconds) will give you direct conversion from seconds to hours with out consideration for days. Minus the hours for days you already got i.e., day24*. You now got remaining hours.
The same for minute and second. You need to subtract the already got hour and minutes, respectively.
The simplest way:
Scanner in = new Scanner(System.in);
System.out.println("Enter seconds ");
int s = in.nextInt();
int sec = s % 60;
int min = (s / 60) % 60;
int hours = (s / 60) / 60;
System.out.println(hours + ":" + min + ":" + sec);
Have a look at the class:
org.joda.time.DateTime
This allows you to do things like:
old = new DateTime();
new = old.plusSeconds(500000);
System.out.println("Hours: " + (new.Hours() - old.Hours()));
However, your solution probably can be simpler:
You need to work out how many seconds in a day, divide your input by the result to get the days, and subtract it from the input to keep the remainder.
You then need to work out how many hours in the remainder, followed by the minutes,
and the final remainder is the seconds.
This is the analysis done for you, and now you can focus on the code.
You need to ask what s/he means by "no hard coding". Generally it means pass parameters, rather than fixing the input values. There are many ways to do this, depending on how you run your code. Properties are a common way in Java.
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");
}
}
You can use the Java enum TimeUnit to perform your math and avoid any hard-coded values. Then we can use String.format(String, Object...) and a pair of StringBuilder(s) as well as a DecimalFormat to build the requested output. Something like,
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a number of seconds: ");
String str = scanner.nextLine().replace("\\,", "").trim();
long secondsIn = Long.parseLong(str);
long dayCount = TimeUnit.SECONDS.toDays(secondsIn);
long secondsCount = secondsIn - TimeUnit.DAYS.toSeconds(dayCount);
long hourCount = TimeUnit.SECONDS.toHours(secondsCount);
secondsCount -= TimeUnit.HOURS.toSeconds(hourCount);
long minutesCount = TimeUnit.SECONDS.toMinutes(secondsCount);
secondsCount -= TimeUnit.MINUTES.toSeconds(minutesCount);
StringBuilder sb = new StringBuilder();
sb.append(String.format("%d %s, ", dayCount, (dayCount == 1) ? "day"
: "days"));
StringBuilder sb2 = new StringBuilder();
sb2.append(sb.toString());
sb2.append(String.format("%02d:%02d:%02d %s", hourCount, minutesCount,
secondsCount, (hourCount == 1) ? "hour" : "hours"));
sb.append(String.format("%d %s, ", hourCount, (hourCount == 1) ? "hour"
: "hours"));
sb.append(String.format("%d %s and ", minutesCount,
(minutesCount == 1) ? "minute" : "minutes"));
sb.append(String.format("%d %s.", secondsCount,
(secondsCount == 1) ? "second" : "seconds"));
System.out.printf("You entered %s seconds, which is %s (%s)%n",
new DecimalFormat("#,###").format(secondsIn), sb, sb2);
Which, when I enter 500000, outputs the requested (manual line break added for post) -
You entered 500,000 seconds, which is 5 days, 18 hours,
53 minutes and 20 seconds. (5 days, 18:53:20 hours)
I started doing some pseudocode and came up with this:
import java.util.Scanner;
public class Project {
public static void main(String[] args) {
// Variable declaration
Scanner scan = new Scanner(System.in);
final int MIN = 60, HRS = 3600, DYS = 84600;
int input, days, seconds, minutes, hours, rDays, rHours;
// Input
System.out.println("Enter amount of seconds!");
input = scan.nextInt();
// Calculations
days = input/DYS;
rDays = input%DYS;
hours = rDays/HRS;
rHours = rDays%HRS;
minutes = rHours/MIN;
seconds = rHours%MIN;
// Output
if (input >= DYS) {
System.out.println(input + " seconds equals to " + days + " days " + hours + " hours " + minutes + " minutes " + seconds + " seconds");
}
else if (input >= HRS && input < DYS) {
System.out.println(input + " seconds equals to " + hours + " hours " + minutes + " minutes " + seconds + " seconds");
}
else if (input >= MIN && input < HRS) {
System.out.println(input + " seconds equals to " + minutes + " minutes " + seconds + " seconds");
}
else if (input < MIN) {
System.out.println(input + " seconds equals to seconds");
}
scan.close();
}

Categories