How to use the TimeUnit class in Java?

0

I have the following exercise that asks me to create a method that given a number of seconds, the program expresses it in Days, Hours, Minutes and Seconds. I found this code in StackOverflow:

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

but I can not use TimeUnit .

    
asked by Die Duro 19.06.2017 в 04:15
source

1 answer

3

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

TimeUnit tu=TimeUnit.DAYS; 

TimeUnit is an enum. When we call TimeUnit.DAYS or any other unit, it returns TimeUnit. TimeUnit has a conversion method that can convert the given long value into the unit of time required. TimeUnit has timedJoin. Normal join function in java, wait for a thread until the thread finishes its work, but timedJoin waits only until a moment and then the control of the thread versions of call.

TimeUnit.SECONDS.timedJoin(th, 5); 

This is a complete code example.

TimeUnitTest.java

package com.GilbertoQuintero;
import java.util.concurrent.TimeUnit;
public class TimeUnitTest {
    public static void main(String... args) throws InterruptedException{
        TimeUnit tu=TimeUnit.DAYS;
        long noOfDays=tu.convert(48,TimeUnit.HOURS);
        System.out.println("noOfDays:"+noOfDays);
        TimeUnit.SECONDS.sleep(2);
        Thread th=new Thread( new TimeUnitTest().new RunnableThread());
        th.start();
        TimeUnit.SECONDS.timedJoin(th, 5);
        System.out.println("done");
    }
  //runnable thread
    class RunnableThread implements Runnable {
        @Override
        public void run() {
            int cnt = 0;
            for (; cnt < 5;cnt++ ) {
                System.out.println("run:" + cnt);
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
    
answered by 19.06.2017 / 07:30
source