Java: convert seconds into day, hour, minute and seconds using TimeUnit

后端 未结 8 1768
我寻月下人不归
我寻月下人不归 2020-12-08 06:25

I am using TimeStamp class to convert seconds into Day,Hours,Minutes,Seconds. I used following code

public static void calculateTime(long seconds) {
                 


        
相关标签:
8条回答
  • 2020-12-08 07:04

    Simple method:

    public static void calculateTime(long seconds) {
        long sec = seconds % 60;
        long minutes = seconds % 3600 / 60;
        long hours = seconds % 86400 / 3600;
        long days = seconds / 86400;
    
        System.out.println("Day " + days + " Hour " + hours + " Minute " + minutes + " Seconds " + sec);
    }
    
    0 讨论(0)
  • 2020-12-08 07:14

    Here is a code i created : (For 3600 seconds it shows "Days:0 Hours:1 Minutes:0 Seconds:0")

    public class TimeConvert 
    {
        public static void main(String[] args) 
        {
            int fsec,d,h,m,s,temp=0,i;
            fsec=3600;
            //For Days
            if(fsec>=86400)
            {
                temp=fsec/86400;
                d=temp;
                for(i=1;i<=temp;i++)
                {
                    fsec-=86400;
                }
            }
            else
            {
                d=0;
            }
            //For Hours
            if(fsec>=3600)
            {
                temp=fsec/3600;
                h=temp;
                for(i=1;i<=temp;i++)
                {
                    fsec-=3600;
                }            
            }
            else
            {
                h=0;
            }
            //For Minutes
            if(fsec>=60)
            {
                temp=fsec/60;
                m=temp;
                for(i=1;i<=temp;i++)
                {
                    fsec-=60;
                }            
            }
            else
            {
                m=0;
            }
            //For Seconds
            if(fsec>=1)
            {
                s=fsec;            
            }
            else
            {
                s=0;
            }
            System.out.println("Days:"+d+" Hours:"+h+" Minutes:"+m+" Seconds:"+s);
        }
    }
    

    Hope it answers your question.

    0 讨论(0)
提交回复
热议问题