Перевод секунд в минуты java

Java: преобразование ввода секунд в часы/минуты/секунды

Вопрос заключается в следующем: “Создайте проект, который читает значение, представляющее собой количество секунд, затем напечатайте эквивалентное количество времени в виде комбинации часов, минут и секунд (например, 9999 секунд эквивалентно 2 часам, 46 минут и 39 секунд.) “

Я до сих пор пробовал следующее

public static void main(String[] args) < Scanner scan = new Scanner(System.in); double totalSecs, seconds, minutes, hours; System.out.println("Enter number of seconds: "); totalSecs = scan.nextInt(); hours = totalSecs/3600; minutes = (Math.abs(Math.round(hours)-hours))*60; seconds = (Math.abs(Math.round(minutes)-minutes))*60; System.out.print(hours + "\n" + minutes + "\n" + seconds); >

Ответ вышел, часы: 2.7775 минут: 13.350000000000009 секунд: 21.00000000000051

Я хочу сделать десятичные числа, скажем, часов, и умножить их на 60, чтобы получить минуты и повторить процесс в течение нескольких секунд. У меня, однако, есть проблемы с этим, поэтому беспорядочное решение (Math.abs) и т.д.

Что бы вы порекомендовали мне изменить/добавить? Благодарю!

Примечание. Это книга для новичков, поэтому я не узнал больше операций, чем те, что я уже сказал в коде. Таким образом, я не понял решения предыдущих времен, этот вопрос задан.

Вот гораздо более простой способ сделать это:

public static void main (String[] args) throws Exception

Примечание. Обратите внимание, что это будет показывать только результат в 24-часовом формате, а если количество часов больше 24, оно будет увеличиваться в течение дня и начнется заново. Например, 30 часов будут отображаться как 06:xx:xx . Кроме того, вам потребуется передать ввод в миллисекундах вместо секунд.

Если вы хотите сделать это по-своему, то вы, вероятно, должны сделать что-то вроде этого:

public static void main (String[] args) throws Exception < long input = 9999; long hours = (input - input%3600)/3600; long minutes = (input%3600 - input%3600%60)/60; long seconds = input%3600%60; System.out.println("Hours: " + hours + " Minutes: " + minutes + " Seconds: " + seconds); >
Hours: 2 Minutes: 46 Seconds: 39 

В качестве альтернативы ответа user2004685;

int seconds = 9999; int hour = 9999 / (60 * 60); //int variables holds only integer so hour will be 2 seconds = 9999 % (60 * 60); // use modulo to take seconds without hours so it will be 2799 int minute = seconds / 60; //same as int variable so minute will be 49 seconds = seconds % 60; // modulo again to take only seconds System.out.println(hour + ":" + minute + ":" + seconds); 

Источник

Convert seconds to hours, minutes and seconds

Now suppose i got time as 5404 which corresponds to 1:30:04. When I divide 5404, I get value as 90.0666666667. 0666666667 is actually 4 seconds to get value as 4 seconds. I convert the data to 60 unites by using percentage formula i.e

I know there is a better solution here.

import java.math.BigDecimal; import java.math.RoundingMode; public class TimeCalc < public static void main(String[] args) < // Inital Time in seconds BigDecimal actualTime = new BigDecimal(5404); // 60 seconds BigDecimal seconds = new BigDecimal(60); // dividing original time to get time in mintues BigDecimal timeinMinutes = actualTime.divide(seconds, 2, RoundingMode.CEILING); // to get value of seconds from minutes double secondsValue = timeinMinutes.doubleValue() - Math.floor(timeinMinutes.doubleValue()); // Seconds will be removed from Minutes to get only Minutes value BigDecimal deductiableSecondValue = new BigDecimal(secondsValue); timeinMinutes = timeinMinutes.subtract(deductiableSecondValue); timeinMinutes = new BigDecimal(Math.ceil(timeinMinutes.doubleValue())); // dividing minutes by 60 to get actual time in hours BigDecimal timeinHours = timeinMinutes.divide(seconds, 2, RoundingMode.CEILING); double hoursdecimalValue = timeinHours.doubleValue(); // suppose time is 1.30 , below code is to get the 30 minutes double minutes = hoursdecimalValue - Math.floor(hoursdecimalValue); // converting value in units of Time since it is always measured wrt 60 minutes = convertDateinTimeUnit(minutes); // suppose time is 1.30 below code is get 1 value String str = new Double(hoursdecimalValue).toString(); str = str.substring(0, str.indexOf('.')); double v = Double.valueOf(str); // converting value in units of Time since it is always measured wrt 60 secondsValue = convertDateinTimeUnit(secondsValue); secondsValue = Math.ceil(secondsValue); minutes = Math.ceil(minutes); System.out.println(" secondsValue " + secondsValue); System.out.println(" minutes decimal value " + minutes); System.out.println(" hours " + v); >static double convertDateinTimeUnit(double value) < double valueInTimeUnit = 60 * value / 100; return valueInTimeUnit * 100; >> 

\$\begingroup\$ If you know the other solution you link to is better, why knowingly implement one that is worse? \$\endgroup\$

Читайте также:  Цвета консоли си шарп

1 Answer 1

 // Inital Time in seconds BigDecimal actualTime = new BigDecimal(5404); 

Why store this in a BigDecimal ? First, you aren’t including a fractional part. Second, it’s just not that big. The thirty-one bits of an int is enough for almost seventy years worth of seconds. Sixty-three bits ( long ) is enough for over two hundred billion years of seconds. You’re only producing hours as output. If you need more than twenty bits, you should probably add at least days if not weeks.

 BigDecimal seconds = new BigDecimal(60); 

This seems like a constant, which you would probably define outside the function.

 private final static int SECONDS_PER_MINUTE = 60; 

I also find the name misleading. When I see seconds , I don’t think that there are sixty seconds in a minute. I think that this is the seconds portion of the time.

Don’t put everything in main

You have more logic in your main method than you should. Part of what makes the other solution better is that it only has two lines in its main method. As a general rule, you want to put all your programming logic in other methods. The main method should just handle input, output, and calling the methods that do the real work.

Why do floating point operations?

 // dividing original time to get time in mintues BigDecimal timeinMinutes = actualTime.divide(seconds, 2, RoundingMode.CEILING); // to get value of seconds from minutes double secondsValue = timeinMinutes.doubleValue() - Math.floor(timeinMinutes.doubleValue()); 

You don’t need floating point operations here. You’re essentially approximating fast integer operations with slower floating point operations.

 int seconds = actualTime; int minutes = seconds / SECONDS_PER_MINUTE; seconds %= SECONDS_PER_MINUTE; 

This also gets rid of all the extraneous doubleValue() and Math.floor calls.

Note that the use of doubleValue reinforces the point that you don’t need BigDecimal . If all your values fit into a double without loss of precision, why put them into a BigDecimal ?

This may work. But I would be worried that the rounding would sometimes cause the wrong value. Particularly since two decimal digits make a repeating fractional part in binary. Perhaps there’s no value that makes this not work, but why take that chance?

Don’t repurpose constants by value

 // dividing minutes by 60 to get actual time in hours BigDecimal timeinHours = timeinMinutes.divide(seconds, 2, RoundingMode.CEILING); 

This is just horrible. It would be better to just say 60 than reuse seconds to mean the number of minutes in an hour.

Читайте также:  Java version outdated please update

Eek

 // suppose time is 1.30 , below code is to get the 30 minutes 

If the hours are 1.30, then that .30 is not 30 minutes. It’s 18 minutes.

 double minutes = hoursdecimalValue - Math.floor(hoursdecimalValue); // converting value in units of Time since it is always measured wrt 60 minutes = convertDateinTimeUnit(minutes); 
 static double convertDateinTimeUnit(double value) < double valueInTimeUnit = 60 * value / 100; return valueInTimeUnit * 100; >

Other than potentially odd rounding effects, the net effect of this method is to multiply value by 60 . I’m not sure what you think is happening here, but you are just multiplying by sixty (with some loss of precision).

A side issue is that this only works for seconds and minutes expressed as fractions of minutes and hours respectively. I’m not sure why you mention «Date» at all.

The camelCase standard has you capitalizing every word after the first, so this would more normally be written convertDateInTimeUnit .

Use Math.floor to truncate

 // suppose time is 1.30 below code is get 1 value String str = new Double(hoursdecimalValue).toString(); str = str.substring(0, str.indexOf('.')); double v = Double.valueOf(str); 
 double hours = Math.floor(hoursDecimalValue.doubleValue()); 

and saved the extra overhead of converting to and from a string. Especially since you were already using Math.floor to calculate this value.

You’re essentially reinventing

 int hours = minutes / MINUTES_PER_HOUR; minutes %= MINUTES_PER_HOUR; 

Only you’re using a lot more code that only approximates these values. If you want the integer mathematics behavior, why not just work with integers?

Binary division

When you store .1 as a binary value, it gets store as a series of bits. Decimal 10 is 1010 in binary. So

Since it repeats, it means that it may not convert back perfectly. For example, if you round to four binary digits, it is .0001 or .0010 (depending on whether you round down or up). The first of those is one sixteenth and the latter is one eighth. If you round to five binary digits, it is .00011, which is exactly 3/32.

Anyway, take .1 and .2, convert to binary rounded to four digits (round up if the next digit is a 1), and then add them. So .0010 + .0011 = .0101, which is 5/16 or .3125. You’re already off by an eightieth. You could be off less with more digits, but you’ll still be off by some small amount.

When you do all your roundabout math operations, these errors are building (and occasionally dropping). I would be concerned that you will occasionally get the wrong answer if you pick a value where it builds errors more than it drops them.

Источник

Переводить секунды в часы, минуты и секунды?

Поэтому я пытаюсь создать программу, которая может конвертировать s из входных данных в h, m и s. мой код до сих пор выглядит так:

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

Хорошо, поэтому я должен был инициализировать s, m, h до 0, потому что если нет, у меня возникли проблемы в операторе if, поэтому я просто установил его на 0, так как я могу изменить его позже:) хорошо. поэтому проблема с этой программой сейчас в том, что если я наберу 3603, я получу этот вывод: 3603 с = 1 ч 60 м 3603 с, если я наберу 3600, я получу это: 3600 с = 1 ч 60 м 3600 с, но вывод должен иметь было 3603 с = 1 ч 0 м 3 с и 3600 с = 1 ч 0 м 0 с соответственно. какие-либо советы / советы / решения о том, как решить эту проблему?:D спасибо заранее!

Читайте также:  Css meta viewport initial scale

11 ответов

Вы никогда не меняли значение s , Быстрая работа будет s = s — (h*3600 + m*60)

РЕДАКТИРОВАТЬ: t = s — (h*3600 + m*60)

 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

Очевидно, вы делаете домашнее задание / практику для изучения Java. Но к вашему сведению, в реальной работе вам не нужно делать эти расчеты и манипуляции. Для этого есть класс.

java.time.Duration

В течение определенного периода времени используйте Duration учебный класс. Вам не нужно делать математику.

Duration d = Duration.ofSeconds( s ); 

Стандартный формат ISO 8601 для строки, представляющей промежуток времени, не привязанный к временной шкале, близок к желаемому результату: PnYnMnDTnHnMnS где P обозначает начало, а T отделяет любые годы-месяцы-дни от любых часов-минут-секунд. Таким образом, полтора часа PT1H30M ,

Классы java.time по умолчанию используют форматы ISO 8601 при разборе или генерации строк.

В Java 9 и более поздних версиях to…Part методы для извлечения отдельных частей часов, минут и секунд.

Java 8 предоставляет отличный API для манипуляции с датой и временем.

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

По сути, этот код добавляет количество секунд к минимальному поддерживаемому значению даты и времени, которое, естественно, имеет значение ЧЧ: мм: сс, равное 00:00:00.

Поскольку вас интересует только время, вы извлекаете его, вызывая toLocalTime() и форматируете его как хотите.

Источник

Java: Convert seconds to hour, minute and seconds

Java Basic Exercises: Convert seconds to hour, minute and seconds

Sample Data:
Input seconds: 86399
23:59:59

Sample Solution:

import java.util.*; public class Main < public static void main(String[] args) < Scanner in = new Scanner(System.in); System.out.print("Input seconds: "); int seconds = in.nextInt(); int S = seconds % 60; int H = seconds / 60; int M = H % 60; H = H / 60; System.out.print( H + ":" + M + ":" + S); System.out.print("\n"); >> 
Input seconds: 86399 23:59:59

Pictorial Presentation:

Pictorial Presentation: Java exercises: Convert seconds to hour, minute and seconds.

Flowchart: JJava exercises: Convert seconds to hour, minute and seconds

Java Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource’s quiz.

Follow us on Facebook and Twitter for latest update.

Java: Tips of the Day

How to call getClass() from a static method in Java?

Just use TheClassName.class instead of getClass()

  • Weekly Trends
  • Java Basic Programming Exercises
  • SQL Subqueries
  • Adventureworks Database Exercises
  • C# Sharp Basic Exercises
  • SQL COUNT() with distinct
  • JavaScript String Exercises
  • JavaScript HTML Form Validation
  • Java Collection Exercises
  • SQL COUNT() function
  • SQL Inner Join
  • JavaScript functions Exercises
  • Python Tutorial
  • Python Array Exercises
  • SQL Cross Join
  • C# Sharp Array Exercises

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook

Источник

Оцените статью