JS中Date与Math类常用操作

  • Date类常用方法
  let date = new Date();

  console.log('当前时间戳',Date.now())
  console.log('当前年份',date.getFullYear())
  console.log('当前月份',date.getMonth() + 1) //月份要 + 1
  console.log('当前周几',date.getDay()) //周日是 0
  console.log('当前日期',date.getDate()) //每个月的第几天
  console.log('当前小时',date.getHours())
  console.log('当前分钟',date.getMinutes())
  console.log('当前秒',date.getSeconds())
  console.log('当前毫秒',date.getMilliseconds())

  //将字符创转换为日期
  var date1 = new Date('2020-05-11 10:12:13');
  var date2 = new Date('2020/05/11 10:12:13');
  var date3 = new Date('05/11/2020 10:12:13');

  console.log(date1,date2,date3)

  //修改日期
  var date4 = new Date();
  date4.setTime(date4.getTime() - (1000 * 60 * 5))
  console.log('当前时间5分钟之前',date4)

  var date5 = new Date();
  date5.setTime(date5.getTime() - (1000 * 60 * 60 * 24 * 3))
  console.log('当前时间3天之前',date5)

  var date6 = new Date();
  date6.setTime(date6.getTime() + (1000 * 60 * 60 * 24 * 3))
  console.log('当前时间3天之后',date6)

  var date7 = new Date();
  console.log('ddd',date7)
  date7.setTime(date7.getTime() + (1000 * 60 * 60 * 24 * 30))
  console.log('当前时间1个月之后',date7)
  • Math类常用方法
    console.log('绝对值', Math.abs(-10));
    console.log('开方', Math.sqrt(9));
    console.log('最小值', Math.min(5, 7, 12, 3))
    console.log('最大值', Math.max(5, 7, 12, 3))
    console.log('向上取整', Math.ceil(1.6))
    console.log('向下取整', Math.floor(1.7))
    console.log('四舍五入', Math.round(1.76))
    console.log('四舍五入', Math.round(1.46))
    console.log('生成一个0-1之间的浮点数(不包括0-1)', Math.random())
    console.log('生成一个0-1之间的浮点数(不包括0-1)', Math.random())

    console.log('生成一个0-10之间的数,包括10',Math.round(Math.random() * 10))
    console.log('生成一个0-10之间的数,不包括10',parseInt(Math.random() * 10))

    /**
     * 生成一个m-n之间的随机数,include标志是否包含最后一个数
     * @param m
     * @param n
     * @param include
     */
    function getRandomKeys(m,n,include){
        if (!m || !n){
            throw new Error("参数异常",m,n)
        }
        if (typeof m != 'number' || typeof n != 'number'){
            throw new Error("参数类型异常",m,n)
        }
        if (m > n){
            throw new Error("参数异常",m,n)
        }
        if (m == n){
            return m
        }
        if (include){
            return m + Math.round(Math.random() * (n - m))
        }else {
            return m + parseInt(Math.random() * (n - m))
        }
    }

    console.log(getRandomKeys())
    console.log(getRandomKeys("asd",50))
    console.log(getRandomKeys(20,10))
    console.log(getRandomKeys(20,20))
    console.log(getRandomKeys(20,30))
    console.log(getRandomKeys(20,30,true))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值