Im new, standard beginning, so I'll leave the rest out.
Do I have to convert every int to seconds, or is this right?
Because when I calculated backwards, manually and count the seconds together of the final statement, I get differences in hours.
Thx Casu
Scanner input = new Scanner(System.in);
final int secmin = 60;
final int day = 24;
final int year = 365;
int seconds = input.nextInt();
int minutes = seconds / secmin;
int remainSec = seconds % secmin ;
int hours = minutes / secmin;
int remainMin = hours % secmin;
int days = hours / day;
int remainHours = hours % day;
int years = days / year;
int remainDays = days % year;
if (minutes <= 59)
{
System.out.println(seconds + " seconds is " + minutes +" minutes and " + remainSec + " seconds");
}
else if (hours <= 23)
{
System.out.println(seconds + " seconds is " + hours +" hours and " + remainMin + " minutes " + remainSec + " seconds");
}
else if (days <= 364)
{
System.out.println(seconds + " seconds is " + days + " days " + remainHours +" hours and " + remainMin + " minutes " + remainSec + " seconds");
}
else
{
System.out.println(seconds + " seconds is " + years + " years " + remainDays + " days " + remainHours +" hours and " + remainMin + " minutes " + remainSec + " seconds");
}
I think this statement needs to be changed :
From "int remainMin = hours % sec min;"
to " int remainMin = minutes % secmin;".
Rest all looks good.
The code looks good. However, I would remove the "Magic Numbers" from the if statements:
Scanner input = new Scanner(System.in);
final int secmin = 60;
final int day = 24;
final int year = 365;
int seconds = input.nextInt();
int minutes = seconds / secmin;
int remainSec = seconds % secmin ;
int hours = minutes / secmin;
int remainMin = hours % secmin;
int days = hours / day;
int remainHours = hours % day;
int years = days / year;
int remainDays = days % year;
if (minutes < secMin)
{
System.out.println(seconds + " seconds is " + minutes +" minutes and " + remainSec + " seconds");
}
else if (hours < day)
{
System.out.println(seconds + " seconds is " + hours +" hours and " + remainMin + " minutes " + remainSec + " seconds");
}
else if (days < year)
{
System.out.println(seconds + " seconds is " + days + " days " + remainHours +" hours and " + remainMin + " minutes " + remainSec + " seconds");
}
else
{
System.out.println(seconds + " seconds is " + years + " years " + remainDays + " days " + remainHours +" hours and " + remainMin + " minutes " + remainSec + " seconds");
}
I know the year/day/hour/minute/second ratios are all pretty static, but what if someone wanted to see your code with 10 seconds to the minute and 10 minutes to the hour? Then you only need to change one place instead of two.
In a production application this could grow to hundreds of locations within the code and chasing down every single one is difficult.
I did enter=
1234234234 s
output=
1234234234 seconds is 39 years 50 days 2 hours and 2 minutes 34 seconds
Sum=
1229904000 s + 4320000 s + 7200 s + 120 s + 34 s = 1234231354 s
Difference =
2880 s
When I change:
int remainMin = hours % secmin; "to" int remainMin = minutes % secmin;
Then:
1234234234 seconds is 39 years 50 days 2 hours and 50 minutes 34 seconds
Result:
48 min add
1229904000 s + 4320000 s + 7200 s + 3000 s + 34 s = 1234234234 s
and the difference is 0.
Thank you for the correction user2006544 and for the improvement Steve.
Related
I want to use count up timer in android for long hours...
Currently, I am using this code, but after some hours, say after 10 hours, the format goes like 10 : 650 :56 (hh:mm:ss)... for lesser time, it works perfectly...
private Runnable updateTimerMethod = new Runnable() {
public void run() {
timeInMillies = SystemClock.uptimeMillis() - startTime;
finalTime = timeSwap + timeInMillies;
int seconds = (int) (finalTime / 1000);
int minutes = seconds / 60;
int hours = minutes / 60;
seconds = seconds % 60;
int milliseconds = (int) (finalTime % 1000);
String timer = ("" + String.format("%02d", hours) + " : "
+ String.format("%02d", minutes) + " : "
+ String.format("%02d", seconds));
myHandler.postDelayed(this, 0);
sendLocalBroadcast(timer);
}
};
Your code for minutes is almost right, but you have to modulus it by 60 just like you do for seconds. Otherwise your value is going to still include all the hours.
Use this function:
private static String timeConversion(int totalSeconds) {
final int MINUTES_IN_AN_HOUR = 60;
final int SECONDS_IN_A_MINUTE = 60;
int seconds = totalSeconds % SECONDS_IN_A_MINUTE;
int totalMinutes = totalSeconds / SECONDS_IN_A_MINUTE;
int minutes = totalMinutes % MINUTES_IN_AN_HOUR;
int hours = totalMinutes / MINUTES_IN_AN_HOUR;
return hours + " : " + minutes + " : " + seconds;
}
You can found other solution in:
https://codereview.stackexchange.com/q/62713/69166
In the textbook it explains how to convert seconds into minutes with how many seconds remain but the question I have is as follows.
Write a program that prompts the user to enter the minutes (e.g., 1
billion), and displays the number of years and days for the minutes.
For simplicity, assume a year has 365 days. Here is an example.
Enter the number of minutes: 100000000
100000000 minutes is approximately 1902 years and 214 days.
What I currently have is as follows:
import java.util.Scanner;
public class Ch2_Exercise2_7 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Prompt user for number of minutes
System.out.println("Enter the number of minutes:");
int minutes = input.nextInt();
// Number of minutes in a year
int year = minutes / 525600;
int day = minutes / 1440;
int remainingMinutes = day % 525600;
System.out.println(minutes + " minutes is " + year + " years and " + remainingMinutes + " days ");
}
}
With what I have it isn't giving me the remaining minutes into days. For example, if I put in 525600 minutes it gives me 1 year and 365 days when it should just be 1 year.
I'm using Java Eclipse. Any help would be greatly appreciated! My apologies in advance if I post the code incorrectly.
You screwed up a bit over here:
// Number of minutes in a year
int year = minutes / 525600;
int day = minutes / 1440;
int remainingMinutes = day % 525600;
You took the total number of minutes and divided by 1440, so the number of days you got was wrong. You should have taken the remainder and then divided by 1440.
Another thing was in your print statement. You wrote the number of minutes left after one year as the number of days.
This should work:
// Number of minutes in a year
int year = minutes / 525600;
int remainingMinutes = minutes % 525600;
int day = remainingMinutes / 1440;
System.out.println(minutes + " minutes is approximately " + year + " years and " + day + " days.");
My main method is separate:
public class MinutesToYearsDaysCalculator {
public static void printYearsAndDays(long minutes) {
double days = minutes / 60 / 24;
double years = days / 365;
double remainingDays = days % 365;
System.out.println((minutes < 0 ? "Invalid Value" : minutes + " min = " + (int) years + " y and " + (int) remainingDays + " d"));
}
}
int mins,hours,remainingDays,days,years;
cout << "Enter minutes:";
cin >> mins;
hours = mins/60;
days = hours/24;
years = days/365;
remainingDays = days % 365;
cout << years << " years " << remainingDays << " days " << endl;
return 0;
public class MinutesToYearsDaysCalculator {
public static void printYearsAndDays(long minutes)
{
if(minutes<0) System.out.println("Invalid Value");
else
{
long hours = minutes/60;
long day = hours/24;
long years = day/365;
long remainingDays = day % 365;
System.out.println(minutes +" min = "+ years+" y and "+remainingDays +" d");
}
}
import java.util.Scanner;
public class Prog13 {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
System.out.println("Enter The Minute");
int min=sc.nextInt();
int year= min/(365*24*60);
int remaining_min=(min%24*60*60);
int day=remaining_min/24*60;
System.out.println( min + " " + " Minutes is approximately:"+ year + " " +"year"+ ' '+ day + "Day" );
}
}
hello you can use this result
import java.util.Scanner;
public class MinToYearsAndDays {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("number of minutes:");
int minutes = input.nextInt();
int year = minutes / 525600;
int remainingMinutes = minutes % 525600;
int day = (remainingMinutes / 1440);
System.out.println(minutes + " minutes is approximately " + year + " years and " + day + " days ");
}
}
public class Mints_to_days_years {
// Given some numbers of minutes calculate the number of days and years
// from the given minutes.
// 1hr = 60 minutes
// 1 day = 24 hours
// 1 year = 365 days
public static void find_days_years(long minutes) {
if(minutes < 0) {
System.out.println("Invalid number of minutes.");
}
// to find the number of years, divide the nminutes by total numbers of minutes in a year.
long years = minutes / (60 * 24 * 365);
// then find the remainder minutes that does not goes exactly into year
long years_remainder = minutes % (60 * 24 * 365);
// divide the remainder by number of minutes in a day to find the numbers of days
long days = years_remainder / (60 * 24);
System.out.println(minutes + " mints = " + years + " yrs and " + days + " days.");
}
public static void main(String[] args) {
find_days_years(525600);
find_days_years(1051200);
find_days_years(561600);
}
}
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();
}
This code below is used to format milliseconds. The calculations are off by a long shot. I need some help with it. Output of my code is below as well as the milliseconds into a Date class.
public static void main(String[] args) {
System.out.println("Wrong Time: " + getTime(999999999 * 599));
}
//Being called into this method is milliseconds = 598999999401
public static String getTime(long miliseconds) {
int years = (int) ((miliseconds / (1000*60*60*24*7*52*12)));
int months = (int) (miliseconds / (1000*60*60*24*7*52) % 12);
int weeks = (int) ((miliseconds / (1000*60*60*24*7)) % 52);
int days = (int) ((miliseconds / (1000*60*60*24)) % 7);
int hours = (int) ((miliseconds / (1000*60*60)) % 24);
int minutes = (int) ((miliseconds / (1000*60)) % 60);
int seconds = (int) (miliseconds / 1000) % 60;
Date date = new Date(598999999401L);//This gets the real time
System.out.println("Right Time: " + date.getYear() + " years " + (int)(date.getMonth() % 12) + " months " + (int)(date.getDay() % 52) + " weeks "
+ (int)(date.getDay() % 7) + " days " + (int)(date.getHours() % 24) + " hours " + (int)(date.getMinutes() % 60) + " minutes " +
+ (int)(date.getSeconds() % 60) + " seconds");
return (years <= 0 ? "" : years + " year" + (years != 1 ? "s" : "")) +
(months <= 0 ? "" : " " + months + " month" + (months != 1 ? "s" : "")) +
(weeks <= 0 ? "" : " " + weeks + " week" + (weeks != 1 ? "s" : "")) +
(days <= 0 ? "" : " " + days + " day" + (days != 1 ? "s" : "")) +
(hours <= 0 ? "" : " " + hours + " hour" + (hours != 1 ? "s" : "")) +
(minutes <= 0 ? "" : " " + minutes + " minute" + (minutes != 1 ? "s" : "")) +
(seconds <= 0 ? "" : " " + seconds + " second" + (seconds != 1 ? "s" : ""));
}
Correct Output(Date class)
Right Time: 88 years 11 months 6 weeks 6 days 14 hours 53 minutes 19 seconds
Wrong Output(My method)
Wrong Time: 1 month 3 weeks 2 days 3 hours 25 minutes 45 seconds
UPDATE 1 (NEW CALCULATIONS)(Still has logic errors):
int years = (int) ((miliseconds / (1000*60*60*24*7*4*12)));
int months = (int) (miliseconds / (1000*60*60*24*7*4) % 12);
int weeks = (int) ((miliseconds / (1000*60*60*24*7)) % 4);
int days = (int) ((miliseconds / (1000*60*60*24)) % 7);
int hours = (int) ((miliseconds / (1000*60*60)) % 24);
int minutes = (int) ((miliseconds / (1000*60)) % 60);
int seconds = (int) (miliseconds / 1000) % 60;
Two issues.
Your code seems to reflect a belief that there are 52 weeks in a month. These are the two lines at fault.
int years = (int) ((miliseconds / (1000*60*60*24*7*52*12)));
int months = (int) (miliseconds / (1000*60*60*24*7*52) % 12);
Also, you're using int where you should be using long. The maximum int number of milliseconds is just under 25 days, so you can never do date/time arithmetic with int.
One problem is int overflow since your main method is using int literals, not longs. Try:
System.out.println("Wrong Time: " + getTime(999999999L * 599L));
Also, don't use magic numbers. Use constants that make sense and that make your code self-commenting:
private static final int MILI_PER_SEC = 1000;
private static final int SEC_PER_MIN = 60;
private static final int MIN_PER_HR = 60;
private static final int HR_PER_DAY = 24;
private static final int DAYS_PER_YR = 365;
and then,
int years = (int) (miliseconds / (MILI_PER_SEC * SEC_PER_MIN * MIN_PER_HR *
HR_PER_DAY * DAYS_PER_YR));
Also, your calculations are all off. You shouldn't be using weeks in the year calculation at all. Use constants, have them make sense. And how do you know that the "correct" result is in fact correct? You are using deprecated code, and Date doesn't use miliseconds the way that you think that it does. It calculates the date relative to January 1, 1970, 00:00:00 GMT as per the Date API.
I have a date that has the format:
"yyyy-MM-dd'T'HH:mm:ss'Z'"
I'd like to convert it to something similar to:
"3 minutes ago"
How can I go about doing this?
See this SO question:
How can I calculate a time span in Java and format the output?
Ugly, but does the trick.. and yes, a duplicate! :(
public static void main(String[] args) {
Calendar c = Calendar.getInstance();
c.set(2010, 10, 20, 22, 37, 12);
Date start = c.getTime();
Date end = new Date();
long diff = (end.getTime() - start.getTime()) / 1000;
long days = diff / (60 * 60 * 24);
long hours = diff / (60 * 60) - days * 24;
long minutes = diff / 60 - (hours * 60 + days * 24 * 60);
long seconds = diff % 60;
String output = "";
if (days >= 1)
output += days + " day" + ((days > 1) ? "s" : "");
if (hours >= 1)
output += " " + hours + " hour" + ((hours > 1) ? "s" : "");
if (minutes >= 1)
output += " " + minutes + " minute" + ((minutes > 1) ? "s" : "");
if (seconds >= 1)
output += " " + seconds + " second" + ((seconds > 1) ? "s" : "");
output = output.trim();
System.out.println(output);
}
For oarsing the date, check How to parse a date?
For displaying it in a nicer format, check for PrettyTime.