Math
对象
不是构造函数,它具有数学常数和函数的属性和方法,跟数学相关
相关方法:
属性、方法名
| 功能 |
Math.PI
| 圆周率 |
Math.floor() | 向下取整 |
Math.ceil() | 向上取整 |
Math.round() | 四舍五入版 就近取整 负数是 五舍六入 |
Math.abs() | 绝对值 |
Math.max() | 求最大值 |
Math.min() | 求最小值 |
Math.random() | 获取范围在 0 ~ 1 内的随机数(含 0 不含 1) |
事例:
console.log(Math.PI); // 3.1415926...
console.log(Math.floor(5.6)); // 5
console.log(Math.ceil(5.6)); // 6
console.log(Math.round(5.5)); // 6
console.log(Math.round(-5.5)); // -5
console.log(Math.abs(-5)); // 5
console.log(Math.max(1,2,3)); // 3
console.log(Math.min(1,2,3)); // 1
console.log(Math.random()); // 0 ~ 1 随机小数
Date
对象和
Math
对象不一样,
Date
是一个构造函数,所以使用时需要实例化后才能使用其
中具体方法和属性。
Date
实例用来处理日期和时间。、
使用
Date
实例化日期对象:
获取当前时间必须实例化
获取指定时间的日期对象
let now = new Date();
let time = new Date('2020/10/1')
// 注意:如果创建实例时并未传入参数,则得到的日期对象是当前时间对应的日期对象
相关方法:
方法名
| 说明 | 代码 |
getFullYear() | 获取当年 | time.getFullYear() |
getMonth() | 获取当月(0 ~ 11) | time.getMonth() |
getDate() | 获取当天日期 | time.getDate() |
getDay() | 获取星期几(周日 0 到周六 6) | time.getDay() |
getHours() | 获取当前小时 | time.getHours() |
getMinutes() | 获取当前分钟 | time.getMinutes() |
getSeconds() | 获取当前秒钟 | time.getSeconds() |
事例:
let time = new Date();
console.log(time.getFullYear()); // 返回当前日期的年 2021
console.log(time.getMonth() + 1); // 月份 返回的月份小 1 个月,记得月份加 1
console.log(time.getDate()); // 返回 几号
console.log(time.getDay()); // 周一返回 1 周六返回 6 周日返回 0
console.log(time.getHours()); // 返回 时
console.log(time.getMinutes()); // 返回 分
console.log(time.getSeconds()); // 返回 秒
时间戳:
时间戳是指
格林威治时间
1970
年
01
月
01
日
00
时
00
分
00
秒
(
北京时间
1970
年
01
月
01
日 08 时
00
分
00
秒
)
起至现在的总毫秒数。
获取时间戳的三种方法:
// 实例化 Date 对象
let now1 = new Date();
console.log(now1.valueOf())
console.log(now1.getTime())
// 2. 简单写可以这么做 (最常用的)
let now2 = + new Date();
console.log(now2);
// 3. HTML5 中提供的方法,有兼容性问题
let now3 = Date.now();
console.log(now3);
谢谢大家观看,希望对大家有所帮助 >w<``