js在一个时间范围内产生一个随机时间

本文介绍如何使用JavaScript的Math.random()方法结合Date对象,在给定的时间范围内生成一个随机时间,包括日期和时间的格式化处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

js使用使用到Math.random()方法实现在一个时间范围内产生一个随机时间。

/*在时间范围内产生一个随机时间*/
function randomDate(start, end) {
  if (start != null && end != null) {
    const _start = new Date(start).getTime();
    const _end = new Date(end).getTime();
    const differ = _end - _start;
    const time_stamp = Math.random() * differ;
    const time = _start + time_stamp;
    //格式化时间
    const datetime = new Date();
    datetime.setTime(time);
    const year = datetime.getFullYear();
    const month = datetime.getMonth() + 1 < 10 ? '0' + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
    const date = datetime.getDate() < 10 ? '0' + datetime.getDate() : datetime.getDate();
    const hour = datetime.getHours() < 10 ? '0' + datetime.getHours() : datetime.getHours();
    const minute = datetime.getMinutes() < 10 ? '0' + datetime.getMinutes() : datetime.getMinutes();
    const second = datetime.getSeconds() < 10 ? '0' + datetime.getSeconds() : datetime.getSeconds();
    return year + '-' + month + '-' + date + ' ' + hour + ':' + minute + ':' + second;
  } else {
    return '---';
  }
}


//调用方法
//console.info('开始时间:' + start_.value + '\n' + '结束时间:' + end_.value + '\n' + '随机生成时间:' + randomDate(start_.value, end_.value));
  

运行效果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值