-2

I just want to convert seconds to proper time format.

e.g. if it is 30 seconds, then it is just displayed as 30 seconds. if it is 80 seconds, it will be displayed as 1 minute 20 seconds It is similar when it is larger than one hour and one day.

Of course it is simple to implement by myself, just just wonder whether there's any existed library I can leverage. Thanks

zjffdu
  • 25,496
  • 45
  • 109
  • 159
  • `java.util.Date`, `java.text.DateFormat/SimpleDateFormat`, and the entire `java.time` package. You don't seem to have looked very hard. – user207421 Dec 31 '19 at 05:01
  • Does this answer your question? [Convert seconds value to hours minutes seconds?](https://stackoverflow.com/questions/6118922/convert-seconds-value-to-hours-minutes-seconds) I posted a new answer for you [here](https://stackoverflow.com/a/59568939/5772882). – Ole V.V. Jan 02 '20 at 19:30

1 Answers1

1

TimeUnit belongs to the package java.util.concurrent. TimeUnit has come in java since JDK 1.5. TimeUnit plays with a unit of time. TimeUnit has many units like DAYS, MINUTES, SECONDS, etc.

But it doesn't directly convert seconds to min, days, hours... So, you can refer my code below to convert seconds to minutes, days, and hours.

import java.util.concurrent.TimeUnit;
import java.util.Scanner;
public class Time {

public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    int seconds = keyboard.nextInt();
    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);
  }}

` Hope this code help you!