走在前端的大道上前端
這是我以前學習時候的一篇筆記,如今整理一下發出來,但願對剛入門前端的朋友有所幫助,前端老司機請請忽略本篇文章學習
記得我剛學js的時候只知道Date的一些常見的用法,有多常見?spa
var date = new Date()//獲取當前時間 let Y = date.getFullYear(); let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1); let D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate(); let h = date.getHours() < 10 ? '0' + date.getHours() : date.getHours(); let m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes(); let s = date.getSeconds();
後來在一些項目或者文章發現了一些新方法,這也是我這篇文章想傳遞給小白的code
1.經過 new Date(2018,1,23) 獲取時間ip
var a = new Date(2018,1,23) console.log(a) //Fri Feb 23 2018 00:00:00 GMT+0800 (CST) var a = new Date(2018,1,24) console.log(a) //Sat Feb 24 2018 00:00:00 GMT+0800 (CST) var a = new Date(2018,0,24) console.log(a) //Wed Jan 24 2018 00:00:00 GMT+0800 (CST) var a = new Date(2018,13,24) console.log(a) //Sun Feb 24 2019 00:00:00 GMT+0800 (CST) var a = new Date(2018,11,24,23,11) console.log(a) //Mon Dec 24 2018 23:11:00 GMT+0800 (CST)
若是你想獲取某個月的最後一天怎麼辦?好比2018年的2月get
var a = new Date(2018,2,0) console.log(a) //Wed Feb 28 2018 00:00:00 GMT+0800 (CST) a.getDate() //28
2.經過 new Date('2018-1-24') 獲取時間it
注意這種寫法的兼容性,在safari 和 iOS 系統下 不支持 - 這種寫法,保險起見 使用 / ,如2018/1/1(2018/01/01,2018/1/01)console
var a = new Date('2018-1-24') console.log(a) //Wed Jan 24 2018 00:00:00 GMT+0800 (CST) var a = new Date('2018-12-24 1:12:14') console.log(a) //Mon Dec 24 2018 01:12:14 GMT+0800 (CST) var a = new Date('2018-0-24') console.log(a) //Invalid Date var a = new Date('2018-13-24') console.log(a) //Invalid Date var a = new Date('2018-12-24 23:12:14') console.log(a) //Mon Dec 24 2018 23:12:14 GMT+0800 (CST)
3.經過 Date.parse('2018-12-1') 獲取時間
注意這種寫法的兼容性,在safari 和 iOS 系統下 不支持 - 這種寫法,保險起見 使用 / ,如2018/1/1(2018/01/01,2018/1/01)入門
var a = Date.parse('2018-12-1') console.log(a) //1543593600000 var a = Date.parse('2018-12-1 13:13:12') console.log(a) //1543641192000 var a = new Date('2018-12-1 13:13:12') console.log(a) //Sat Dec 01 2018 13:13:12 GMT+0800 (CST) var a = new Date('2018-12-1 13:13:12').getTime() console.log(a) //1543641192000 var a = Date.parse('2018-13-1') console.log(a) //NaN