前言:最近在做一個日期選擇功能,在日期轉換的時候經常換到暈,總結一下常用的Date對象的相關用法,方便日後直接查看使用~ 1. new Date()的使用方法有: 不接收任何參數:返回當前時間; 接收一個參數x: 返回1970年1月1日 + x毫秒的值。 new Date(1, 1, 1)返回190 ...
前言:最近在做一個日期選擇功能,在日期轉換的時候經常換到暈,總結一下常用的Date對象的相關用法,方便日後直接查看使用~
1. new Date()的使用方法有:
-
- 不接收任何參數:返回當前時間;
- 接收一個參數x: 返回1970年1月1日 + x毫秒的值。
- new Date(1, 1, 1)返回1901年2月1號。
- new Date(2016, 1, 1)不會在1900年的基礎上加2016,而只是表示2016年2月1號。
2. 使用new Date(time) 將時間轉換成 Date 對象
註意:time格式需要為 1999/12/31 23:59 (不能為1999-12-30 23:43),否則在一些機型下可能會報錯。
3. date對象一些常用的api
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 沒有原生提供但卻經常需求使用的功能
- 根據日期獲取當前星期幾
//參數 日期 getWeek(day) { const weekArr = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']; return weekArr[day]; } getWeek(new Date(x).getDay())
- 獲取某個時間+1個小時,直接對小時數進行加1可能會溢出,因此先轉換成 Date 對象,再使用setHours 改變小時。
new Date(x).setHours(new Date(x).getHours()+1,new Date(x).getMinutes());
- 為了統一格式,返回日期是10以下,需在前面補0.
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");