js中Math.Date的一些常用方法

Math对象常用的一些方法了解 1.Math.PI 圆周率(π) 2.求最大值和最小值 Math.max , Math.min 3.取整的方法: Math.ceil 向上取整,如果是负数,取大的那个数 Math.floor 向下取整, 如果是负数,取小的值 Math.round 四舍五入 取整的方法,其实还有一种会经常用到,那就是parseInt,取整,舍弃小数位 4.Math.random() 取值范围是[0,1) 求0-N的随机数, parseInt(Math.random()*(N+1)); 其他还有一些方法,Math.abs 求绝对值 Math.pow(a,b) a的b次方 Math.sqrt 开方 js中提供的是Date构造函数,可以创建日期对象 var now = new Date(); 获取的是当前的时间 在创建日期的时候,我们也可以指定具体的时间 var date = new Date('2019-5-27 23:30:00'); 我们可以通过获取日期里的各个组成部分,自定义日期格式 var now = new Date(); 1.获取年 getFullYear var year = now.getFulYear(); 2.获取月 getMonth var month = now.getMonth(); 注意:是从0开始,范围是0-11 3.获取日 getDate var date = now.getDate(); 4.获取一周中的第几天 getDay var day = now.getDay(); 范围是0-6, 0是周日,1周一 5.时 getHours var hours = now.getHours(); 6.分 getMinutes var minutes = now.getMinutes(); 7.秒 getSeconds var seconds = now.getSeconds(); var str = year + '年' + month + '月' + day + '日, ' + hours + '时' + minutes + '分' + seconds + '秒'; console.log(str); 还有一个概念叫做时间戳:就是数字格式的日期,便于计算,一般用于求时间差。时间戳即距离1970年1月1日0分0秒,所过去的毫秒数。 一般会用在统计一段代码的执行时间(优化性能),或者秒杀倒计时 第一种,统计一段代码的执行时间 var begin = new Date(); var sum = 0; for(var i=1; i<= 100;i++) {sum+= i;} var end = new Date(); console.log(sum); console.log(end - begin); 第二种计算一下距离下课还有多长时间 var now = new Date(); var future = new Date("2019-5-28 12:00:00"); var time = parseInt((future - now)/1000); var hours = parsenInt(time/3600); var minutes = parseInt(time/60)%60; var seconds = time%60; var str = "距离下课还有: " + hours + '时' + minutes + '分' + seconds + '秒'; document.write(str);

猜你喜欢

转载自www.cnblogs.com/z-lin/p/10934479.html