1. 程式人生 > >秒轉化為天小時分秒字串的java實現和js實現

秒轉化為天小時分秒字串的java實現和js實現

需求描述:將秒轉化為天小時分秒字串顯示,例如:3660s --> 1小時1分0秒

java實現:

/**
     * 秒轉化為天小時分秒字串
     *
     * @param seconds
     * @return String
     */
    public static String formatSeconds(long seconds) {
        String timeStr = seconds + "秒";
        if (seconds > 60) {
            long second = seconds % 60;
            long min = seconds / 60;
            timeStr = min + "分" + second + "秒";
            if (min > 60) {
                min = (seconds / 60) % 60;
                long hour = (seconds / 60) / 60;
                timeStr = hour + "小時" + min + "分" + second + "秒";
                if (hour > 24) {
                    hour = ((seconds / 60) / 60) % 24;
                    long day = (((seconds / 60) / 60) / 24);
                    timeStr = day + "天" + hour + "小時" + min + "分" + second + "秒";
                }
            }
        }
        return timeStr;
    }

js實現:

/**
 * 秒轉為 天小時分秒
 * @param second_time
 * @return
 */
function formatSeconds(second_time) {
    if (isNaN(second_time)) {
        return "0秒";
    }
    var timeStr = parseInt(second_time) + "秒";
    if (parseInt(second_time) > 60) {
        var second = parseInt(second_time) % 60;
        var min = parseInt(second_time / 60);
        timeStr = min + "分" + second + "秒";
        if (min > 60) {
            min = parseInt(second_time / 60) % 60;
            var hour = parseInt(parseInt(second_time / 60) / 60);
            timeStr = hour + "小時" + min + "分" + second + "秒";
            if (hour > 24) {
                hour = parseInt(parseInt(second_time / 60) / 60) % 24;
                var day = parseInt(parseInt(parseInt(second_time / 60) / 60) / 24);
                timeStr = day + "天" + hour + "小時" + min + "分" + second + "秒";
            }
        }
    }
    return timeStr;
}