日期
获取日期是一个很简单的操作,但我们需要将日期对象进行处理,处理成我们需要的格式,放在任何地方。
首先,简单介绍一下日期对象。
日期对象:获取的是本地电脑的时间(注意是一个对象,不是字符串)
console.log( new Date());
console.dir( new Date());//可以看出是一个对象
//结果如下:
//Fri May 08 2020 09:38:37 GMT+0800 (中国标准时间)
常用日期对象的使用:
let date = new Date();
//年月日时分秒(获取的都是数字)
console.log( date.getFullYear());//年
console.log( date.getMonth()+1);//月,从0开始,获取当前月要+1
console.log( date.getDate());//日
console.log( date.getHours());//时
console.log( date.getMinutes());//分
console.log( date.getSeconds());//秒
//星期(返回数字)
//0-6:周日-周六
console.log( date.getDay());//周几
//转换成国际标准时间字符串
console.log( date.toUTCString());
还可以设置时间:时间戳
console.log( new Date(2020,4,8));
//Fri May 08 2020 00:00:00 GMT+0800 (中国标准时间)
console.log( new Date(2020,4,8,20,0,0));
//Fri May 08 2020 20:00:00 GMT+0800 (中国标准时间)
console.log( new Date(2020,1));
//Sat Feb 01 2020 00:00:00 GMT+0800 (中国标准时间)
//只有一个参数时,会认为是一个毫秒数
console.log( new Date(2020));
//Thu Jan 01 1970 08:00:02 GMT+0800 (中国标准时间)
//默认时间Thu Jan 01 1970 08:00:00 GMT+0800 (中国标准时间)
日期对象
和 数字做减法——>得到相差的毫秒数
和 别的时间做减法——>得到相差的毫秒数
let date = new Date();
console.log( date-0);
//当前时间毫秒数:1588903751019
let birthday = new Date(2000,3,20);
console.log( date-birthday);
//生日与现在相差的毫秒数:632743941011