0
点赞
收藏
分享

微信扫一扫

【7. Math和Date】

何以至千里 2022-02-28 阅读 23
javascript

Math和Date

Math

Math的常用方法

【1】 Math.random()   随机,生成一个[0, 1)的随机数
【2】 Math.round()    四舍五入
【3】 Math.ceil()     向上取整
【4】 Math.floor()    向下取整  
【5】 Math.pow(n1,n2) 计算n1的n2次方   n1**n2
【6】Math.sqrt()      开平方
【7】 Math.max(...arr) 求这一对数据当中的最大值 
【8】 Math.min(...arr) 求这一对数据当中的最小值
【9】 Math.abs()       求绝对值
【10】Math.PI 圆周率 3.1415

Date

常用方法

const date = new Date()    // 创建Date对象 Mon Feb 27 2022 18:03:00 GMT+0800 (中国标准时间)
date.getFullYear()         // 年 2022
date.getMonth() + 1        // 月 2
date.getDate()  		   // 日 27
date.getDay()              // 周日 0
date.getHours()			   // 时 18
date.getMinutes()		   // 分 3
date.getSeconds()          // 秒 0
date.getTime()             // 获取当前时间到格林威治时间的时间差(以毫秒数为单位数字)
						   // 格林威治时间:1970年1月1号0:00:00

格式化日期时间

const dateFormat = (date = '', fmt = 'yyyy-MM-dd hh:mm:ss') => {
  if (Object.prototype.toString.call(date) !== '[object Date]') return '-'
  const opt = {
    'y+': `${date.getFullYear()}`, // 年
    'M+': `${date.getMonth() + 1}`, // 月
    'd+': `${date.getDate()}`, // 日
    'h+': `${date.getHours()}`, // 时
    'm+': `${date.getMinutes()}`, // 分
    's+': `${date.getSeconds()}`, // 秒
  }
  Object.keys(opt).forEach((k) => {
    const ret = new RegExp(`${k}`).exec(fmt)
    if (ret) {
      fmt = fmt.replace(ret[1], opt[k].padStart(ret[1].length, '0'))
    }
  })
  return fmt
}
console.log(dateFormat(new Date()))

上一篇 6. 对象

举报

相关推荐

0 条评论