欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

[js常用]将秒转化为时分秒

程序员文章站 2022-06-24 22:58:13
内容引入至网络 ......

内容引入至网络

<!doctype html>    
    <html>    
    <head>    
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />    
    <title>秒转换为时分秒</title>  
<script src="http://code.jquery.com/jquery-1.11.2.js"></script>    
    </head>    
  
    <body>  
  
<input type="text" id="demo1">s  
<button id="btn">转换</button>  
<input type="text" id="demo2">或  
<input type="text" id="demo3">  
  
    
    <script language="javascript">  
/**  
* 将秒数换成时分秒格式   
*/  
    
function formatseconds(value) {  
    var thetime = parseint(value);// 秒  
    var thetime1 = 0;// 分  
    var thetime2 = 0;// 小时  
    if(thetime > 60) {  
        thetime1 = parseint(thetime/60);  
        thetime = parseint(thetime%60);  
            if(thetime1 > 60) {  
            thetime2 = parseint(thetime1/60);  
            thetime1 = parseint(thetime1%60);  
            }  
    }  
        var result = ""+parseint(thetime)+"秒";  
        if(thetime1 > 0) {  
        result = ""+parseint(thetime1)+"分"+result;  
        }  
        if(thetime2 > 0) {  
        result = ""+parseint(thetime2)+"小时"+result;  
        }  
    return result;  
}  
  
function formatseconds2(a) {   
  var hh = parseint(a/3600);  
  if(hh<10) hh = "0" + hh;  
  var mm = parseint((a-hh*3600)/60);  
  if(mm<10) mm = "0" + mm;  
  var ss = parseint((a-hh*3600)%60);  
  if(ss<10) ss = "0" + ss;  
  var length = hh + ":" + mm + ":" + ss;  
  if(a>0){  
    return length;  
  }else{  
    return "nan";  
  }  
}  
</script>    
<script>  
$("#btn").on( "click", function( event ) {  
  var x = $("#demo1").val();  
  var y = formatseconds(x);  
  $("#demo2").val(y);  
$("#demo3").val(formatseconds2(x));  
});  
</script>  
    </body>    
    </html>