珠峰培训

Math函数&Date函数

作者:jw

2016-07-10 23:01:03

178

Math函数

1 、Math方法

Math.abs();取绝对值

Math.ceil();向上取整

Math.floor();向下取整

Math.round();四舍五入 在负数情况下五及五以下是舍

Math.max(val1,val2,val3…);求最大值

Math.min(val1,val2,val3…);求最小值

Math.abs(-12);
Math.ceil(12.5);
Math.floor(12.5);
Math.round(12.4);
Math.min(11,12,13,14,15);
Math.max(11,12,13,14,15);

2、 随机数

Math.random(); 获取[0,1)之间的随机小数(包含0不包含1)

获取[m,n]之间的随机整数

Math.round(Math.random()*(n-m)+m);  //公式

Date函数

1、 获取时间

1、获取电脑时间

var time = new Date();  //获取当前电脑时间
var year = time.getFullYear();
var month = time.getMonth()+1; // 获得0-11
var day = time.getDate();
var week = time.getDay(); //0-6之间,代表周日到周六
var hours = time.getHours();
var minutes = time.getMinutes();
var seconds = time.getSeconds();
var msecond = time.getMilliseconds();

2、 获取目标时间,在Date()中传参数

var targetTime = new Date("2016-06-20 21:00:00");

Date()支持十多种传入时间格式,在日期中用”-“可以连接时间,但是在IE6/7/8中不兼容,需要改成”/”

var targetTime = new Date("2016/06/20 21:00:00");

2、 计算倒计时

getTime(); 获取当前时间距离1970年1月1日午夜(00:00)到现在的毫秒差

则用目标时间距离1970年的毫秒差 减去 当前时间距离1970年的毫秒差,则是目标时间与当前时间之间的差值