国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

JS將時間秒轉換成天小時分鐘秒的字符串

2024-05-06 15:37:04
字體:
來源:轉載
供稿:網友

項目中需求是這樣,接口返回的數據中時間單位為秒,但前端顯示的時候需要更人性化的帶有單位(天,小時,分鐘,秒)的字符串;

轉換函數如下:

/** * 格式化秒 * @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;}            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 玉屏| 巴彦县| 于都县| 仁寿县| 石林| 新丰县| 读书| 兴义市| 诸暨市| 大厂| 富源县| 微山县| 美姑县| 格尔木市| 镶黄旗| 大石桥市| 台前县| 高要市| 宁晋县| 红河县| 垫江县| 沂南县| 清河县| 克山县| 延庆县| 龙山县| 玉门市| 西城区| 紫金县| 武邑县| 临西县| 舟曲县| 吉木萨尔县| 许昌县| 桦川县| 土默特左旗| 阳曲县| 东辽县| 桂阳县| 黑龙江省| 玉树县|