js秒數格式化
阿新 • • 發佈:2018-11-27
前端經常會從後端獲取到時間,比如我今天就碰到,後端只返回秒數,只能我自己轉義,就寫了個小方法,把3921轉化為1小時5分鐘21秒這樣的格式,總的來說就是不斷遍歷自身的秒數。用起來非常的簡單!!!
var secdons = 3921 var timeFormat = '' function timeFilter(secdons){ if (secdons<60){ var sec sec = (secdons>0)?secdons + '秒':'' timeFormat = timeFormat + sec return; } else if(secdons<3600){ var min min = Math.floor(secdons/60) //console.log(min) timeFormat = timeFormat + min + '分鐘' timeFilter(secdons-min*60) } else{ var hour hour = Math.floor(secdons/3600) timeFormat = timeFormat + hour + '小時' timeFilter(secdons-hour*3600) } } timeFilter(secdons) console.log(secdons) console.log(timeFormat)