Math对象属于Javascript内置对象,无需实例化(不需要添加new ),可以直接使用
方法
1. Math.round(number) //四舍五入整数
2. Math.ceil(number) //向上取整
3. Math.floor(number) //向下取整
4. Math.random() //随机返回0.0~1.0之间的数
5. Math.max(x,y) //求最大值
6. Math.min(x,y) //求最小值 7. Math.pow(x,y) //求xy
-
获取指定范围的随机数
公式:Math.floor(Math.random()*(max-min+1))+min
封装一个获取指定范围的随机数
function getRand(min,max){
return Math.floor(Math.random()*(max-min+1)+min);
}
创建Date对象
var dateObj=new Date();
方法
将日期转为字符串
toLocaleString() toLocaleDateString()
toLocaleTimeString()
toLocaleString特殊用法:可以将一串数字转为xxx,xxx,xxx这种有间隔的方法
console.log((123264849.12).toLocaleString('en-US')); // 123,264,849.12
2 获取年、月、日、小时、分、秒
- 1)getYear() //两位的年(2000年前)或三位的年[1900] 获取两位数的年,从1900年开始计算,现在这个方法基本上已经没弃用
console.log(d.getYear());
- 2)getFullYear() //四位的年 获取完整的四位数的年,使用的比较多
console.log(d.getFullYear());
- 3)getMonth() //月份+1 获取月份,返回值为0-11,表示1月到12月,所以获取到月份之后需要+1
console.log(d.getMonth()+1); // 当前月+1
- 4)getDate() //日 获取天,返回值为今天是几号
console.log(d.getMonth()+1); // 当前月+1
- 5)getHours() //小时
console.log(d.getHours()); // 当前月+1
- 6)getMinutes() //分钟
console.log(d.getMinutes()); // 当前分钟
- 7)getSeconds() //秒
console.log(d.getMinutes()); // 当前秒钟
8)getTime() //1970 年 1 月 1 日至今的毫秒数 时间戳专门用来计算时间的差值,或者倒计时等功能
var d = new Date(); // 1. 通过getTime获取 console.log(d.getTime()); // 当前秒钟 // 2. 通过valueOf获取 console.log(d.valueOf()); // 3. H5新增的获取毫秒树的方式 console.log(Date.now()); // 4. 添加+号[把日期对象转为数字类型] console.log(+new Date());
3怎么计算时间差 使用时间戳
公式:计算公式 d = parseInt(总秒数/60/60/24) // 天数
h = parseInt(总秒数/60/60%24) // 小时
m = parseInt(总秒数/60%60) // 分钟
s = parseInt(总秒数%60) // 秒
4直接设置年月日,时分秒
var d = new Date('2009-11-12 08:20:30'); // 正常字符串时间的表示方式
var d = new Date('Ja·n 1 2001 05:20:10'); // 日期时间对象返回的格式
var d = new Date(2020,10,10,10,20,30); // js的时间格式
var d = new Date(1607061589000); // 时间戳
5set ...简单设置时间
setMonth(); setDate(); setFullYear();
案例:输入年份生成日历
<style> body { text-align: center; } .box { margin: 0 auto; width: 880px; } .title { background: #ccc; } table { height: 200px; width: 200px; font-size: 12px; text-align: center; float: left; margin: 10px; font-family: arial; } </style> <script> var year = parseInt(prompt('输入年份:', '2022')); // 制作弹窗输入年份,默认为2022年 document.write(calendar(year));//调用函数生成指定年份的年历 function calendar(year){ var html = "<div class='box'>"; for(var m=0;m<=11;m++){ // 获取每月的第一天的星期 var w = new Date(year,m).getDay(); html += `<table><tr class="title"><td colspan='7'>${year}年${m}月</td></tr>`; html += `<tr><td>日</td><td>一</td><td>二</td><td>三</td><td>四</td><td>五</td><td>六</td></tr>`; // 获取每月的天数 var max = new Date(year,m,0).getDate(); html += '<tr>' for(var d=1; d <= max; d++){ //如果该月的第1天不是星期日,则填充空白 if (w && d == 1) { html += '<td colspan ="' + w + '"> </td>'; } html += '<td>' + d + '</td>'; if (new Date(year,m,d).getDay()==6) {//如果星期六不是该月的最后一天,则换行 html += '</tr><tr>'; } else if (d == max) {//该月的最后一天,闭合</tr>标签 html += '</tr>'; } } html += '</tr>' } html += '</table></div>'; return html; } </script>