js將日期格式轉換為YYYY-MM-DD HH:MM:SS
阿新 • • 發佈:2020-09-21
1、百度不少js將日期格式轉換為YYYY-MM-DD HH:MM:SS 。可是都略顯複雜,所以這裡總結了一下,自己找到的,方便自己學習和使用。
方法一:
專案原始碼: $("#createTime").text((new Date(jumpParams.createDate.time).Format("yyyy-MM-dd hh:mm:ss"))); $("#updateTime").text((new Date(jumpParams.updateDate.time).Format("yyyy-MM-dd hh:mm:ss"))); 關鍵點: xxx.Format("yyyy-MM-dd hh:mm:ss");呼叫這句話就可以將Sun May 27 2018 11:08:09 GMT+0800 (中國標準時間)格式的時間轉換為"2018-05-27 11:08:09"格式的時間。
方法二:
專案原始碼: $("#createTime").text((ChangeDateFormat(new Date(jumpParams.createDate.time)))); $("#updateTime").text((ChangeDateFormat(new Date(jumpParams.updateDate.time)))); 封裝方法呼叫: function ChangeDateFormat(date) { return date.Format("yyyy-MM-dd hh:mm:ss"); }
關鍵點:
注意括號和自己的時間格式即可。
可以使用瀏覽器工具,對轉換進行檢視:
其他方法
function formatDate(date,cut) { var date = new Date(date); var YY = date.getFullYear() + cut; var MM = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + cut; var DD = date.getDate() < 10 ? "0" + date.getDate() : date.getDate(); var hh = (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":"; var mm = (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) + ":"; var ss = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds(); return YY + MM + DD + " " + hh + mm + ss; }
正則方法
function farmatDate(time,fmt) { if (/(y+)/.test(fmt) { fmt = fmt.replace(RegExp.$1,date.getFullYear() + '').substr(4 - RegExp.$1.length); } let o = { 'M+': getMonth() + 1,'d+': getDay(),'h+': getHours(),'m+': getMinutes(),'s+': getSeconds() }; for (let key in o) { if(RegExp(`(${key})`.test(fmt)) { let str = o[key] + ''; fmt = fmt.replace(RegExp.$1,str.length === 2 ? str:padLeftZero(str); } } return fmt; } // 函式 padLeftZero 的作用:如果月份為1位(如9),則在其左邊補0(變為09) function padLeftZero(str) { return '00' + substr(str.length); } // 舉例 let res = formatDate('1469261964000','yyyy-MM-dd hh:mm'); console.log(res); // 2016-07-06 16:19
到此這篇關於js將日期格式轉換為YYYY-MM-DD HH:MM:SS的文章就介紹到這了,更多相關js YYYY-MM-DD HH:MM:SS內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!