七、Date 日期对象 ------ 2020-03-15

2020-03-15  本文已影响0人  自己写了自己看

1、日期对象的基本操作:

new Date();  // 标准的时间格式

/**
*  获取的是客户端(本机电脑)本地的时间,这个时间用户是可以
*  自己修改的,所以不能作为重要的参考依据;
*/

Sun Mar 15 2020 15:30:45 GMT+0800 (中国标准时间)
/**
* 这个结果不是字符串是对象数据类型的,属于日期对象
* 或者说是 Date 这个类的实例;
*/
typeof new Date() // 'object'

2、标准日期对象中提供的一些属性和方法,供我们操作日期信息

(1)getFullYear()  // 获取年

(2)getMonth()  // 获取月
// 结果是0-11代表一月到十二月

(3)getDate() // 获取日

(4)getDay()  // 获取星期
// 结果是 0-6 代表周日到周六

(5)getHours()  // 获取小时

(6)getMinutes()  // 获取分

(7)getSeconds()  // 获取秒

(8)getMilliseconds()  // 获取毫秒

(9)getTime()  // 获取当前日期距离 1970/01/01 00:00:00 
// 这个日期之间的毫秒差

(10)toLocalDateString()  // 获取年月日(字符串)

(11)toLocalString()  // 获取完整的日期字符串

3、格式化日期字符串

/**
* new Date() 除了获取本机时间,还可以把一个时间格式字符串转换为
* 标准的时间格式
*/

new Date('2020-3-15');
// Sun Mar 15 2020 00:00:00 GMT+0800 (中国标准时间)

/**
*  new Date() 支持的日期格式
*  yyyy/mm/dd
*  yyyy-mm-dd 这种格式在IE下不支持
*  yyyy-mm-dd hh:mm:ss
*/

4、万能的格式化日期字符串方法

String.prototype.formatTime = function (template) {
    // 初始化模板
    typeof template === 'undefined' ? 
    template = "{0}年{1}月{2}日 {3}:{4}:{5}" : null;
    
    // this 是我们要处理的字符串
    let matchAry = this.match(/\d+/g);
    template = template.replact(/\{(\d+)\}/g, (x, y) => {
       let val = matchAry[y] || "00";
       val.length < 2 ? val = "0" + val : null;
       return val;
    })
   return template;
}
上一篇 下一篇

猜你喜欢

热点阅读