Date 對象算是較常用的對象之一,但很多人完全不會操作,就算一些簡單的操作也用 moment 而不自己嘗試一下。
本次分享下 Date 中的 date 使用技巧,希望能給大家啟發。
MDN官網介紹
setDate() 方法根據本地時間來指定一個日期對象的天數。
如果 dayValue 超出了月份的合理范圍,setDate 將會相應地更新 Date 對象。
例如,如果為 dayValue 指定0,那么日期就會被設置為上個月的最后一天。
獲取月份天數
// 獲取月份天數function getMonthDayCount(year, month) { return new Date(year, month, 0).getDate();}console.log(getMonthDayCount(2017, 10)); // 31
Date 第三個參數的本質跟 setDate 是一樣的。
因為 date 為 0 時自動退到上個月的最后一天,所以這里月份也不需要減,正好的。
獲取所有月份天數
function getAllMonthDayCount(year) { var days = [31, new Date(year, 2, 0).getDate(), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; return days;}console.log(getAllMonthDayCount(2016));// [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
這個算是上面的延伸,不多解釋。
是否是閏年
function isLeapYear(year) { return (year % 4 == 0) && (year % 100 != 0 || year % 400 == 0);}
這是網上的代碼,相信大多數人都用。
但其實你真的理解或者能記住么?
反正我不能。。
function isLeapYear(year) { return new Date(year, 2, 0).getDate() === 29;}console.log([ isLeapYear(2000), isLeapYear(2016), isLeapYear(2017), isLeapYear(2018)]); // [ true, true, false, false ]
這樣看,是不是就非常簡單容易理解了。
而且都不需要記,是不是想忘都忘不了?
天數加減操作
之前看到有人用相對秒數在計算幾天前或幾天后,甚至還在算跨月,跨年的情況。
其實直接 setDate 就好了,自動處理 跨月,跨年 的情況。
// 10天后是幾月幾號var dt = new Date('2016-12-25');dt.setDate(dt.getDate() + 10);console.log(dt.toLocaleDateString()); // 2017/1/4// 10天前是幾月幾號var dt = new Date('2017-01-04');dt.setDate(dt.getDate() - 10);console.log(dt.toLocaleDateString()); // 2016/12/25
小結
雖然這些東西很基礎,說方法名,可能大家都知道,但很多人卻依然不會去使用。
就跟用 jq 卻依然 for 循環處理結果一樣。
這里只列舉了部分例子,也許會有其他神奇的操作技巧等你去發現。
新聞熱點
疑難解答