小編給大家分享一下JS如何將時間秒轉換成天小時分鐘秒的字符串,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
項目中需求是這樣,接口返回的數據中時間單位為秒,但前端顯示的時候需要更人性化的帶有單位(天,小時,分鐘,秒)的字符串;
轉換函數如下:
/** * 格式化秒 * @param int value 總秒數 * @return string result 格式化后的字符串 */ function formatSeconds(value) { var theTime = parseInt(value);// 需要轉換的時間秒 var theTime1 = 0;// 分 var theTime2 = 0;// 小時 var theTime3 = 0;// 天 if(theTime > 60) { theTime1 = parseInt(theTime/60); theTime = parseInt(theTime%60); if(theTime1 > 60) { theTime2 = parseInt(theTime1/60); theTime1 = parseInt(theTime1%60); if(theTime2 > 24){ //大于24小時 theTime3 = parseInt(theTime2/24); theTime2 = parseInt(theTime2%24); } } } var result = ''; if(theTime > 0){ result = ""+parseInt(theTime)+"秒"; } if(theTime1 > 0) { result = ""+parseInt(theTime1)+"分"+result; } if(theTime2 > 0) { result = ""+parseInt(theTime2)+"小時"+result; } if(theTime3 > 0) { result = ""+parseInt(theTime3)+"天"+result; } return result; }
ps:下面看下js時間戳與時間日期間相互轉換
今天在工作中要將獲取到的時間轉換為時間戳,一時間竟不知道怎么用,于是不得不去查詢資料,這里特地做個筆記。
1、將日期轉換為時間戳。
要將日期轉換為時間戳,首先得先獲取到日期,這里可以直接指定日期,或者是使用當前日期。要獲取當前日期,我們可以使用new Date()來獲取。直接上代碼。
// (1)、將當前日期轉換為時間戳。 var now = new Date(); console.log(now.getTime()) // 將當前日期轉換為時間戳,getTime()方法可返回距1970年1月1日之間的毫秒數。也可以使用 +now ,該效果等同于now.getTime() // (2)、將指定日期轉換為時間戳。 var t = "2017-12-08 20:5:30"; // 月、日、時、分、秒如果不滿兩位數可不帶0. var T = new Date(t); // 將指定日期轉換為標準日期格式。Fri Dec 08 2017 20:05:30 GMT+0800 (中國標準時間) console.log(T.getTime()) // 將轉換后的標準日期轉換為時間戳。
2、將時間戳轉換為日期。
var t = 787986456465; // 當參數為數字的時候,那么這個參數就是時間戳,被視為毫秒,創建一個距離1970年1月一日指定毫秒的時間日期對象。 console.log(new Date(t)) // Wed Dec 21 1994 13:07:36 GMT+0800 (中國標準時間) var t2 = "2017-5-8 12:50:30"; console.log(new Date(t2)) // Mon May 08 2017 12:50:30 GMT+0800 (中國標準時間) var t3 = "2017-10-1"; console.log(new Date(t3)) // Sun Oct 01 2017 00:00:00 GMT+0800 (中國標準時間) 不設定時分秒,則默認轉換為00:00:00
將時間戳轉換為指定格式日期的方法封裝:
// 格式化日期,如月、日、時、分、秒保證為2位數 function formatNumber (n) { n = n.toString() return n[1] ? n : '0' + n; } // 參數number為毫秒時間戳,format為需要轉換成的日期格式 function formatTime (number, format) { let time = new Date(number) let newArr = [] let formatArr = ['Y', 'M', 'D', 'h', 'm', 's'] newArr.push(time.getFullYear()) newArr.push(formatNumber(time.getMonth() + 1)) newArr.push(formatNumber(time.getDate())) newArr.push(formatNumber(time.getHours())) newArr.push(formatNumber(time.getMinutes())) newArr.push(formatNumber(time.getSeconds())) for (let i in newArr) { format = format.replace(formatArr[i], newArr[i]) } return format; }
如需要調用上述方法,使用formatTime(1545903266795, 'Y年M月D日 h:m:s')
或者formatTime(1545903266795, 'Y-M-D h:m:s')即可
以上是“JS如何將時間秒轉換成天小時分鐘秒的字符串”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。