JS常用獲取時間方式
阿新 • • 發佈:2020-11-04
在未來的程式設計中,總會遇到各種各樣的獲取時間的要求,下面我們來看一下獲取不同時間格式的方法有哪些???
如果不記得的話建議收藏哦!!!
1、獲取當前的日期和時間
方法:new Date()
console.log(new Date())//Wed Nov 04 2020 18:20:49 GMT+0800 (中國標準時間)
2、獲取當前日期
可執行程式碼:
console.log(new Date().toLocaleDateString())//2020/11/4
不一樣的格式:
function fn(){ let t = new Date() let fn1 = (d) =>('0'+d).substr(-2) console.log(t.getFullYear()+'-'+ fn1(t.getMonth()+1)+'-'+ fn1(t.getDate())) ) } fn()//2020-11-04
說明:b.substr(-2)的含義是將字串b字串從後面數起,返回倒數兩位的字元
箭頭函式可參考:https://www.liaoxuefeng.com/wiki/1022910821149312/1031549578462080
3、返回當前時間
獲取的是12小時制:
console.log(new Date().toLocaleTimeString())//下午6:23:09
獲取的是24小時制:
console.log(new Date().toLocaleTimeString('chinese', { hour12: false}))//18:45:50
4、從Date()物件返回當前 年份
console.log(new Date().getFullYear())//2020
5、從Date()物件返回當前 月份
注意:月份的返回值範圍是 0~11,所以要獲得當前月份,要+1
console.log(new Date().getMonth())//當前月份-1
console.log(new Date().getMonth()+1)//當前月份
6、從Date()物件返回月份的當前 日
console.log(new Date().getDate())//返回當前 日
7、從Date()物件返回一個星期的某一天,當前是星期幾
注意:獲取的返回值範圍是 0~6 , 0表示星期天
console.log(new Date().getDay())
8、從Date()物件的 當前 小時
注意:獲取返回值的範圍是 0~23
console.log(new Date().getHours())//小時
9、返回Date()物件的 當前 分鐘
注意:獲取返回值的範圍是 0~59
console.log(new Date().getMinutes())//分
9、返回Date()物件的 當前 秒數
注意:獲取返回值的範圍是 0~59
console.log(new Date().getSeconds())//秒
10、返回Date()物件的 當前 毫秒數
注意:範圍是 0~999
console.log(new Date().getMilliseconds())//毫秒
11、返回 日期 1970.01.01 距現在的毫秒數
console.log(new Date().getTime())