- Math
Math 和其他的对象不同,它不是一个构造函数,不需要创建对象。所以我们不需要 通过 new 来调用,而是直接使用里面的属性和方法即可。
Math属于一个工具类,里面封装了数学运算相关的属性和方法。如下
Date
# 写法一:不传递参数时,则获取系统的当前时间对象
代码解释:不传递参数时,表示的是获取系统的当前时间对象。也可以理解成是:获取当前代码执行的时间。
代码举例:
var date1 = new Date();
console.log(date1);
console.log(typeof date1)
打印结果:
Mon Feb 17 2020 21:57:22 GMT+0800 (中国标准时间)
object
# 写法二:传递参数
传递参数时,表示获取指定时间的时间对象。参数中既可以传递字符串,也可以传递数字,也可以传递时间戳。
通过传参的这种写法,我们可以把时间字符串/时间数字/时间戳,按照指定的格式,转换为时间对象。
举例1:(参数是字符串)
const date11 = new Date('2023/01/30 09:15:00');
console.log(date11); // Fri Feb 17 2023 21:00:00 GMT+0800 (中国标准时间)
const date12 = new Date('2023/01/30');
console.log(date12); // Mon Jan 30 2023 00:00:00 GMT+0800 (中国标准时间)
const date13 = new Date('2023/01/30');
console.log(date13); // Mon Jan 30 2023 00:00:00 GMT+0800 (中国标准时间)
const date14 = new Date('Mon Jan 30 2023 00:00:00 GMT+0800 (中国标准时间)');
console.log(date14); // Mon Jan 30 2023 00:00:00 GMT+0800 (中国标准时间)
日期的格式化
# Date对象的方法
Date对象 有如下方法,可以获取日期和时间的指定部分:
代码举例:
const myDate = new Date();
console.log(myDate); // 打印结果:Mon Jan 30 2023 09:20:06 GMT+0800 (中国标准时间)
console.log(myDate.getFullYear()); // 打印结果:2023
console.log(myDate.getMonth() + 1); // 打印结果:1
console.log(myDate.getDate()); // 打印结果:30
const dayArr = ['星期日', '星期一', '星期二', '星期三', '星期四','星期五', '星期六'];
console.log(myDate.getDay()); // 打印结果:1
console.log(dayArr[myDate.getDay()]); // 打印结果:星期一
console.log(myDate.getHours()); // 打印结果:9
console.log(myDate.getMinutes()); // 打印结果:20
console.log(myDate.getSeconds()); // 打印结果:51
console.log(myDate.getMilliseconds()); // 打印结果:501
console.log(myDate.getTime()); // 获取时间戳。打印结果:1675041696562