JS学习七:一些内置对象Math、Date

Math对象:

console.log(Math.round(3.6))  //四舍五入,结果:4
console.log(Math.ceil(3.1))  //向上取整,结果:4
console.log(Math.floor(3.1))  //向下取整,结果:3
console.log(Math.max(1,2,3,5))  //取最大值,结果:5
console.log(Math.abs(-3.4))  //取绝对值,结果:3.4
console.log(Math.pow(2, 3)) //取x的y交方,结果:8
console.log(Math.sqrt(2))  //开平方,结果:14.1......
console.log(Math.random())  //取0-1之间的随机数 

 取x-y之间的随机整数,公式:

parseInt(Math.random() * (y - x + 1) + x)

 示例:

console.log(parseInt(Math.random() * (20 - 5 + 1) + 5))   //5-20之间的随机整数
console.log(parseInt(Math.random() * (10 - 1 + 1) + 1))   //1-10之间的随机整数

 

Date对象:

使用Date(),方式一,没有参数,返回字符串:获取当前时间

var d1 = Date();
console.log(d1)  // Nov 18 2018 15:57:54 GMT+0800 (中国标准时间)

 

创建date对象,方式二,可以有参数:

var d1 = new Date();
console.log(d1) //Nov 18 2018 15:59:47 GMT+0800 (中国标准时间),获取当前时间
var d1 = new Date("2015/10/1");
console.log(d1)  //Oct 01 2015 00:00:00 GMT+0800 (中国标准时间)
var d1 = new Date("2015-10-1");
console.log(d1)   // Oct 01 2015 00:00:00 GMT+0800 (中国标准时间)

 

使用:2015-01-01格式的,获取的时侯,将是8点,而不是0点的时侯。

var d1 = new Date("2015-10-01");
console.log(d1)  //Oct 01 2015 08:00:00 GMT+0800 (中国标准时间)

 

使用Date(年,月,日...)格式,有年,月,日参数时月是从0开始计算,0是1月:

var d1 = new Date(2015,9,01,9,10,11);
console.log(d1)   // Oct 01 2015 09:10:11 GMT+0800 (中国标准时间)

 

使用Date(数字)格式,只有一个数字参数时表示从1970.0.0.0.0.0开始加多少毫秒:

var d1 = new Date(2015);
console.log(d1)  //Jan 01 1970 08:00:02 GMT+0800 (中国标准时间)

 

date对象的方法:

var d1 = new Date();
console.log(d1)  //Sun Nov 18 2018 16:14:08 GMT+0800 (中国标准时间)
console.log(d1.getYear(), d1.getMonth(), d1.getDate())  //118 10 18

 

获取date对象的时间戳:

var d1 = new Date();
console.log(d1.getTime())  //1542529002122

 

设置时间:

var d1 = new Date();
d1.setFullYear(2000)
d1.setMonth(5)
d1.setDate(5)
console.log(d1)  //Jun 05 2000 16:18:15 GMT+0800 (中国标准时间)

 时间转换为数字时,年从1970开始计算多少年,月从0开始计算至到11,表示1-12月

转换为时间字符串:

var d = new Date();
var str1 = d.toLocaleString()
console.log(str1)    //2018/11/18 下午4:21:04
var str2 = d.toLocaleTimeString()   
console.log(str2)   //下午4:21:04
var str3 = d.toLocaleDateString()
console.log(str3)   //2018/11/18

 

 

时间运算:

var d1 = new Date();
var d2 = new Date(2016,10,1)
console.log(d1 - d2)   //得到一个毫秒的数值:64599953611

 

posted on 2018-11-18 15:46  myworldworld  阅读(116)  评论(0)    收藏  举报

导航