Java:使用TimeUnit将秒转换为日,小时,分钟和秒

时间:2012-07-06 07:44:21

标签: java datetime time

我正在使用TimeStamp类将秒转换为日,小时,分钟,秒。我使用了以下代码

public static void calculateTime(long seconds) {
        int day = (int)TimeUnit.SECONDS.toDays(seconds);        
        long hours = TimeUnit.SECONDS.toHours(seconds) - TimeUnit.SECONDS.toHours(TimeUnit.SECONDS.toDays(seconds));
        long minute = TimeUnit.SECONDS.toMinutes(seconds) - TimeUnit.SECONDS.toMinutes(TimeUnit.SECONDS.toHours(seconds));
        long second = TimeUnit.SECONDS.toSeconds(seconds) - TimeUnit.SECONDS.toSeconds(TimeUnit.SECONDS.toMinutes(seconds));

        System.out.println("Day " + day + " Hour " + hours + " Minute " + minute + " Seconds " + second);

    }

但我得不到正确的结果。 例如,当我将此方法称为calculateTime(3600)时,它会将结果显示为Day 0 Hour 1 Minute 60 Seconds 3540而不是Day 0 Hour 1 Minute 0 Seconds 0

我的逻辑有什么问题?请帮帮我。

8 个答案:

答案 0 :(得分:88)

应该是

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

修改 说明:

  1. 日计算正确无需解释。
  2. TimeUnit.SECONDS.toHours(秒)将为您提供从秒到小时的直接转换,而无需考虑您已计算的天数。减去你已经有几天的时间,即白天* 24。你现在剩下几个小时了。
  3. 同样的分钟和秒。你需要分别减去已经有的小时和分钟。

答案 1 :(得分:11)

您可以这样做只使用TimeUnit

public static void calculateTime(long seconds) {
    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);
}

或略短但可能不那么直观

public static void calculateTime(long seconds) {
    int day = (int) TimeUnit.SECONDS.toDays(seconds);
    long hours = TimeUnit.SECONDS.toHours(seconds) -
                 TimeUnit.DAYS.toHours(day);
    long minute = TimeUnit.SECONDS.toMinutes(seconds) -
                  TimeUnit.HOURS.toMinutes(TimeUnit.SECONDS.toHours(seconds));
    long second = TimeUnit.SECONDS.toSeconds(seconds) -
                  TimeUnit.MINUTES.toSeconds(TimeUnit.SECONDS.toMinutes(seconds));
    System.out.println("Day " + day + " Hour " + hours + " Minute " + minute + " Seconds " + second);
}

答案 2 :(得分:8)

简单方法:

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

答案 3 :(得分:2)

这是我创建的代码:( 3600秒显示“天数:0小时:1分钟:0秒: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);
    }
}

希望它能回答你的问题。

答案 4 :(得分:1)

后期但有用的

  

以00:00:00的格式获取时间

/**
     * The time in format.
     *
     * in The Format of 00:00:00
     */

public String getTimeInFormat(long _SECONDS)
{
    if(TimeUnit.SECONDS.toHours(_SECONDS)>0)
    {
        return  String.format("%02d:%02d:%02d",
                TimeUnit.SECONDS.toHours(_SECONDS),
                TimeUnit.SECONDS.toMinutes(_SECONDS) -
                        TimeUnit.HOURS.toMinutes(TimeUnit.SECONDS.toHours(_SECONDS)),
                TimeUnit.SECONDS.toSeconds(_SECONDS) -
                        TimeUnit.MINUTES.toSeconds(TimeUnit.SECONDS.toMinutes(_SECONDS)));
    }
    else {
        return  String.format("%02d:%02d",
                TimeUnit.SECONDS.toMinutes(_SECONDS) -
                        TimeUnit.HOURS.toMinutes(TimeUnit.SECONDS.toHours(_SECONDS)),
                TimeUnit.SECONDS.toSeconds(_SECONDS) -
                        TimeUnit.MINUTES.toSeconds(TimeUnit.SECONDS.toMinutes(_SECONDS)));
    }

}

答案 5 :(得分:0)

试试这个

public static void calculateTime(long seconds) {

int day = (int)TimeUnit.SECONDS.toDays(seconds);        
long hours = TimeUnit.SECONDS.toHours(seconds) ;

long tempSec = seconds - (TimeUnit.HOURS.toSeconds(hours) );
System.out.println("after hours calculation "+ tempSec);

long minute = TimeUnit.SECONDS.toMinutes(tempSec); 

if(tempSec > TimeUnit.MINUTES.toSeconds(minute)){
    tempSec = tempSec - (TimeUnit.MINUTES.toSeconds(minute) );          
}else{
    tempSec = TimeUnit.MINUTES.toSeconds(minute) - tempSec;
}
System.out.println("after min calculation "+ tempSec);


long second = TimeUnit.SECONDS.toSeconds(tempSec) ;

System.out.println("Day " + day + " Hour " + hours + " Minute " + minute + " Seconds " + second);
}

答案 6 :(得分:0)

这是我的代码:

public static String secondsToString(TimeUnit greatestUnit, long sourceDuration, TimeUnit sourceUnit) {

    int ordinal = greatestUnit.ordinal();
    if(ordinal<=sourceUnit.ordinal())
        return String.format("%02d", sourceDuration);

    final long greatestDuration = greatestUnit.convert(sourceDuration, sourceUnit);
    final long rest = sourceDuration - sourceUnit.convert(greatestDuration, greatestUnit);

    return String.format("%02d:", greatestDuration) + secondsToString(TimeUnit.values()[--ordinal], rest, sourceUnit);
}

或循环

public static String secondsToStringByLoop(TimeUnit greatestUnit, long sourceDuration, TimeUnit sourceUnit) {

    final StringBuffer sb = new StringBuffer();
    int ordinal = greatestUnit.ordinal();

    while(true){
        if(ordinal<=sourceUnit.ordinal()) {
            sb.append(String.format("%02d", sourceDuration));
            break;
        }

        final long greatestDuration = greatestUnit.convert(sourceDuration, sourceUnit);
//          if(greatestDuration>0 || sb.length()>0)
        sb.append(String.format("%02d:", greatestDuration));

        sourceDuration -= sourceUnit.convert(greatestDuration, greatestUnit);
        greatestUnit = TimeUnit.values()[--ordinal];
    };

    return sb.toString();
}

用法示例:

String str = secondsToString(TimeUnit.DAYS, 1000, TimeUnit.SECONDS);

函数返回:“ 00:00:16:40”(天:小时:分钟:秒)

str = UnitsConverter.secondsToString(TimeUnit.DAYS, 1000, TimeUnit.MINUTES);

返回:“ 00:16:40”(天:小时:分钟)

str = UnitsConverter.secondsToString(TimeUnit.MINUTES, 1000, TimeUnit.SECONDS);

返回:“ 16:40”(分钟:秒)

答案 7 :(得分:-1)

public static void timeCalculator(){


      Scanner input = new Scanner(System.in);
      System.out.print("Enter length of time in seconds: ");
      int n = input.nextInt();
      int nDay = n/86400;
      int nHours = (n%86400)/3600;
      int nMin = ((n%86400)%3600) /60;
      int nSec =(((n%86400)%3600)%60);
      System.out.println();
      System.out.print("That is "+ nDay+ " day(s),"+nHours+"  hour(s), "+nMin+"  minute(s), and "+nSec+" second(s). ");
}