计算开始与结束时间的时长:x天x时x分x秒

发布时间 2023-11-14 18:13:13作者: 活出自己范儿
import java.util.Date;
/**
 @ClassName: DateDurationUtils
 @Description: 时长计算工具类
 @Author: lizg
 @Date: 2023/11/10 14:39
 */
public class DateDurationUtils {
    private static Long DAY_SECOND_VALUE = 24 * 60 * 60 * 1000L;
    private static Long HOUR_SECOND_VALUE = 60  * 60 * 1000L;
    private static Long MINUTE_SECOND_VALUE = 60 * 1000L;
    private static Long SECOND_VALUE = 1000L;
    /**
     时间间隔: 天时分秒
     @param  duration
     @return
     */
    public static String getDuration(Long duration) {
        duration = duration == null ? 0L : duration;
        StringBuilder timeDuration = new StringBuilder();
        String[] durationArray = new String[]{"天", "时", "分", "秒"};
        int[] durationValue = new int[4];
        durationValue[0] = (int) (duration / DAY_SECOND_VALUE);
        durationValue[1] = (int) (duration % DAY_SECOND_VALUE / HOUR_SECOND_VALUE);
        durationValue[2] = (int) (duration % HOUR_SECOND_VALUE / MINUTE_SECOND_VALUE);
        durationValue[3] = (int) (duration % MINUTE_SECOND_VALUE / SECOND_VALUE);
        for (int i = 0; i < durationValue.length; i++) {
            timeDuration.append(durationValue[i] + durationArray[i]);
        }
        return timeDuration.toString();
    }
    /**
     求两个日期的时间间隔:天时分秒
     @param  startTime
     @param  endTime
     @return
     */
    public static String getDuration(Date startTime, Date endTime) {
        if (startTime == null || endTime == null) {
            return null;
        }
        if (startTime.after(endTime)) {
            return null;
        }
        long duration  = endTime.getTime() - startTime.getTime();
        return getDuration(duration);
    }


    public static void main(String[] args) {
        Long dur = 29032 * 1000L;
        System.out.println(getDuration(dur));
    }
}


执行结果:
0天8时3分52秒