内置对象Date,是一个构造函数,必须用new 调用
语法:
1. let date = new Date();
console.log(date); //不写参数就是返回系统当前日期
2.let date = new Date('2021-11-15');
console.log(date);
属性:
一、getXXX() 方法 get方法用于获取当前时间
let date=new Date()
1. getFullYear
console.log(date.getFullYear()) 返回当前年份
2. getMonth
console.log('月份:' + (date.getMonth() + 1)); 返回当前月份 一定要+1 它是从0开始
3. getDate
console.log( date.getDate());返回当前几号
4.getDay
console.log(date.getDay());返回当前周几 0是周日 0-6
5.getHours
console.log(date.getHours()); 返回当前小时
6.getMinutes
console.log(date.getMinutes()); 返回当前分钟
7.getSeconds
console.log(date.getSeconds());返回当前秒数
8.getMilliseconds
console.log(date.getMilliseconds()); 返回当前毫秒数
二、setXXX()方法 用于修改日期, 语法格式与get一样
三、时间戳
获取的毫秒总数是距离 1970年1月1日开始算
1. 通过 valueOf() 和 getTime()获取毫秒数
let date = new Date();
console.log(date.valueOf());
console.log(date.getTime());
2.简单写法 +new Date()
let date = +new Date(); new Date前面加个 +号
console.log(date);
3.H5新增的 获得总的毫秒数 低版本不支持
console.log(Date.now());
四、时间运算
两个时间可以进行加减法运算
例如:
let d1 = new Date('1992/5/28') 注意:此处格式没有明确要求 ,用'-' '@' '#' '*' 皆可
let d2 = new Date()
let time = d2 - d1 可以直接进行减法运算
console.log(time); 获取到毫秒数,再进行转换即可
console.log('秒数:' + Math.floor(num / 1000)); 返回秒数
console.log('分钟:' + Math.floor(num / 1000 / 60)); 返回分钟
console.log('小时:' + Math.floor(num / 1000 / 60 / 60)); 返回小时
console.log('天数:' + Math.floor(num / 1000 / 60 / 60 / 24)); 返回天数
五、星期几汉化处理
用getDay获取到的周几是阿拉伯数字,一般我们写星期几都是大写,例如:星期三而不是星期3
解决办法:
如果要用汉字,加一个数组
let arr = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
let day = date.getDay(); 获取到周几就是数组的索引号
console.log(`今天是${year}年${month}月${dates}日,${arr[day]}`); 直接索引即可