Web前端編程入門--js時間轉換
阿新 • • 發佈:2017-09-29
bsp 當前 入門 parse 轉換 orm eth pan ret
時間戳格式轉換
function jsonDateFormat(jsonDate) { //json日期格式轉換為正常格式 var jsonDateStr = jsonDate.toString();//此處用到toString()是為了讓傳入的值為字符串類型,目的是為了避免傳入的數據類型不支持.replace()方法 try { var k = parseInt(jsonDateStr.replace("/Date(", "").replace(")/", ""), 10); if (k < 0) returnnull; var date = new Date(parseInt(jsonDateStr.replace("/Date(", "").replace(")/", ""), 10)); var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1; var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate(); var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(); var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds(); var milliseconds = date.getMilliseconds(); return date.getFullYear() + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds; }catch (ex) { return "時間格式轉換錯誤"; } }
獲取當前時間轉換
function dateTimeDiff(diff) { var myDate = new DateTimeAdd(‘d‘, diff); //獲取當前年 var year = myDate.getFullYear(); //獲取當前月 var month = myDate.getMonth() + 1; //獲取當前日 var date = myDate.getDate(); var h = myDate.getHours(); //獲取當前小時數(0-23) var m = myDate.getMinutes(); //獲取當前分鐘數(0-59) var s = myDate.getSeconds(); var now = year + ‘-‘ + p(month) + "-" + p(date) + " " + p(h) + ‘:‘ + p(m) + ":" + p(s); return now; } /** * 獲取當前時間 */ function p(s) { return s < 10 ? ‘0‘ + s : s; } function DateTimeAdd(strInterval, Number) { var dtTmp = new Date(); switch (strInterval) { case ‘s‘: return new Date(Date.parse(dtTmp) + (1000 * Number)); case ‘n‘: return new Date(Date.parse(dtTmp) + (60000 * Number)); case ‘h‘: return new Date(Date.parse(dtTmp) + (3600000 * Number)); case ‘d‘: return new Date(Date.parse(dtTmp) + (86400000 * Number)); case ‘w‘: return new Date(Date.parse(dtTmp) + ((86400000 * 7) * Number)); case ‘q‘: return new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + Number * 3, dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds()); case ‘m‘: return new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + Number, dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds()); case ‘y‘: return new Date((dtTmp.getFullYear() + Number), dtTmp.getMonth(), dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds()); } }
Web前端編程入門--js時間轉換