Js 获取半小时到1小时之间的随机时间段

2023-09-26  本文已影响0人  匆白

<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>

<script type="text/javascript">

$(function () {

    // 取当前时间的前半小时

    let endTime = new Date(new Date().getTime() - 1 * 30 * 60 * 1000);

    // 取当前时间的前一小时

    let starTime = new Date(new Date().getTime() - 1 * 60 * 60 * 1000);

    console.log('当前时间='+endTime)

    console.log('前一小时='+starTime)

    let day = onGetTimeFrameToTime(starTime,endTime)

    let randomTime = formatDate(day)

    // 获取随机时间

    console.log('随机时间='+randomTime)

});

// 时间格式转换

function formatDate(date) { 

    var y = date.getFullYear();

    var m = date.getMonth() + 1;

    m = m < 10 ? ('0' + m) : m;

    var d = date.getDate();

    d = d < 10 ? ('0' + d) : d;

    var h = date.getHours();

    h=h < 10 ? ('0' + h) : h;

    var minute = date.getMinutes();

    minute = minute < 10 ? ('0' + minute) : minute;

    var second=date.getSeconds();

    second=second < 10 ? ('0' + second) : second;

    return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second; 

}

// 时间格式随机

function onGetTimeFrameToTime (starTime, endTime) {

    let m = new Date(starTime);

    let mt = m.getTime();

    let n = new Date(endTime);

    let nt = n.getTime();

    let s = nt - mt;

    let sm = Math.floor(Math.random() * s);

    return new Date(mt + sm);

}

</script>

上一篇下一篇

猜你喜欢

热点阅读