js 时分秒与秒数的转换

1. 时间戳 格式化为 时分秒(00:00:00)

     /**
     * 时间秒数格式化
     * @param s 时间戳(单位:秒)
     * @returns {*} 格式化后的时分秒
     */
    var sec_to_time = function(s) {
        var t;
        if(s > -1){
            var hour = Math.floor(s/3600);
            var min = Math.floor(s/60) % 60;
            var sec = s % 60;
            if(hour < 10) {
                t = '0'+ hour + ":";
            } else {
                t = hour + ":";
            }

            if(min < 10){t += "0";}
            t += min + ":";
            if(sec < 10){t += "0";}
            t += sec.toFixed(2);
        }
        return t;
    }

2. 时分秒(00:00:00) 转为 时间戳

    /**
     * 时间转为秒
     * @param time 时间(00:00:00)
     * @returns {string} 时间戳(单位:秒)
     */
    var time_to_sec = function (time) {
        var s = '';

        var hour = time.split(':')[0];
        var min = time.split(':')[1];
        var sec = time.split(':')[2];

        s = Number(hour*3600) + Number(min*60) + Number(sec);

        return s;
    };
### 秒数转换时分秒格式的实现 以下是将秒数转换时分秒格式的一种常见方法。通过整除和取余操作来分别提取小时、分钟和剩余的秒数。 #### Java 实现 ```java public class TimeConverter { public static String convertSecondsToTime(int totalSeconds) { int hours = totalSeconds / 3600; int minutes = (totalSeconds % 3600) / 60; int seconds = totalSeconds % 60; return String.format("%d:%02d:%02d", hours, minutes, seconds); } public static void main(String[] args) { int totalSeconds = 7385; // 示例输入 System.out.println(convertSecondsToTime(totalSeconds)); // 输出结果 } } ``` 上述代码定义了一个 `convertSecondsToTime` 方法,该方法接受总秒数作为参数并返回一个字符串形式的时间表示(HH:mm:ss)。这里使用了标准库中的 `String.format` 函数来确保输出格式的一致性[^1]。 #### JavaScript 实现 如果需要在前端或者 Node.js 中完成此功能,则可以采用如下方式: ```javascript function convertSecondsToTime(totalSeconds) { const hours = Math.floor(totalSeconds / 3600); const minutes = Math.floor((totalSeconds % 3600) / 60); const seconds = totalSeconds % 60; return `${hours}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`; } const totalSeconds = 7385; // 示例输入 console.log(convertSecondsToTime(totalSeconds)); // 输出结果 ``` 这段代码同样实现了将秒数转化为 HH:mm:ss 格式的逻辑,并利用了 `padStart` 来保证分钟和秒钟部分始终显示两位数字[^3]。 #### Python 实现 对于喜欢简洁语法的语言使用者来说,Python 提供了一种非常直观的方式来进行这种类型的转换: ```python def convert_seconds_to_time(total_seconds): hours = total_seconds // 3600 remainder = total_seconds % 3600 minutes = remainder // 60 seconds = remainder % 60 return f"{hours}:{minutes:02}:{seconds:02}" total_seconds = 7385 # 示例输入 print(convert_seconds_to_time(total_seconds)) # 输出结果 ``` 在这个例子中,我们再次运用到了简单的算术运算以及字符串格式化技术来构建最终的结果字符串。 ### 结论 以上三种不同语言版本展示了如何有效地把给定数量的秒分解成更易读的形式——即通常所说的“时分秒”。每一种解决方案都遵循相同的数学原理:先求得完整的小时数目;接着处理剩下的分钟数;最后得到不足一分钟的部分也就是具体的秒数[^2]。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值