日期對象的基本操作
-
new Date()
獲取當前客戶端(本機電腦的時間),該時間用戶可以修改,所以不能作為重要的參考依據,獲取的結果不是字符串而是對象數據類型
let time = new Date();
console.log(typeof time); // "object"
- 標準日期對象中提供了一些屬性和方法,以便操作日期信息
-
getFullYear()
:獲取年
-
getMonth()
:獲取月,結果是0-11,分別代表一到十二月
-
getDate()
:獲取日期
-
getDay()
:獲取星期,結果是0-6,代表周日到周六
-
getHours()
:獲取時
-
getMinutes()
:獲取分
-
getSeconds()
:獲取秒
-
getMilliseconds()
:獲取毫秒
-
getTime()
:獲取當前日期距離1970/1/1 00:00:00這個時間之間的毫秒差
-
toLocaleDateString()
:獲取年月日(字符串)
-
toLocaleString()
:獲取完整的日期字符串
-
new Date()
除了獲取本機時間,還可以把一個時間格式的字符串轉換為標準的時間格式
new Date('2019-11-11 11:11:11');
// => Mon Nov 11 2019 11:11:11 GMT+0800 (中國標準時間)
格式化時間字符串方法的封裝
String.prototype.formatTime = function formatTime(template){
typeof template === "undefined" ? template = "{0}年{1}月{2}日 {3}:{4}:{5}" : null;
let arr = this.match(/\d+/g);
template = template.replace(/\{(\d+)\}/g,(x,y) => {
let val = arr[y] || '00';
console.log(y)
val.length < 2 ? val += '0' : null;
return val;
})
return template;
}
let str = '2012-2-16 13:11:12';
console.log(str.formatTime())