前言:最近在作一個日期選擇功能,在日期轉換的時候常常換到暈,總結一下經常使用的Date對象的相關用法,方便往後直接查看使用~javascript
1. new Date()的使用方法有:java
2. 使用new Date(time) 將時間轉換成 Date 對象 api
注意:time格式須要爲 1999/12/31 23:59 (不能爲1999-12-30 23:43),不然在一些機型下可能會報錯。函數
3. date對象一些經常使用的apithis
new Date()轉換以後的數據,能夠直接使用下面的api new Date(x).getMonth()+1 //獲取月份 new Date(x).getDate //獲取日期 new Date(x).getHours() //獲取小時 new Date(x).getMinutes() //獲取分鐘 new Date(x).toLocaleDateString()); // 轉換爲本地日期格式,視環境而定,輸出:2017年07月04日 new Date(x).toLocaleString()); // 轉換爲本地日期和時間格式,視環境而定,輸出:2017年07月04日 上午10:03:05
4. javascript 沒有原生提供但卻常常需求使用的功能spa
//參數 日期 getWeek(day) { const weekArr = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']; return weekArr[day]; } getWeek(new Date(x).getDay())
new Date(x).setHours(new Date(x).getHours()+1,new Date(x).getMinutes());
function getFull(n) { return (n > 9 ? '' : '0') + n; } var x = getFull(3); //03 var y = getFull(11); //11
Date.prototype.Format = function (fmt) { //author: meizz var o = { "M+": this.getMonth() + 1, //月份 "d+": this.getDate(), //日 "h+": this.getHours(), //小時 "m+": this.getMinutes(), //分 "s+": this.getSeconds(), //秒 "q+": Math.floor((this.getMonth() + 3) / 3), //季度 "S": this.getMilliseconds() //毫秒 }; if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); for (var k in o) if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); return fmt; } // 調用: var time1 = new Date().Format("yyyy-MM-dd"); var time2 = new Date().Format("yyyy-MM-dd hh:mm:ss");