JS格式化时间(获取两个日期之间的每一天、每一月、每一秒)

把时间戳转换为时间

// 时间戳转换为时间
function timestampToTime(timestamp, isMs = true) {
    const date = new Date(timestamp * (isMs ? 1 : 1000))
    return `${date.getFullYear()}-${date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`
}

获取当天过去每半小时的时间

function formatTodayHalfHours(nowDate = +new Date()) { 
    var timeStamp = new Date(new Date().setHours(0, 0, 0, 0));
    var dateList = []; 

    while (nowDate > timeStamp) {
        var hour = new Date(nowDate).getHours() < 10 ? '0' + new Date(nowDate).getHours() : new Date(nowDate).getHours();
        var minute = new Date(nowDate).getMinutes() < 31 ? '00' : '30';
        dateList.unshift(hour + ':' + minute + ':' + '00'); 
        nowDate -= 30 * 60 * 1000
    }
    return dateList
}

例如,当天0点 - 12点20分之间没半个小时的时间:

formatTodayHalfHours(+new Date('2019-04-28 12:20:00'))

输出:

[“00:00:00”, “00:30:00”, “01:00:00”, “01:30:00”, “02:00:00”, “02:30:00”, “03:00:00”, “03:30:00”, “04:00:00”, “04:30:00”, “05:00:00”, “05:30:00”, “06:00:00”, “06:30:00”, “07:00:00”, “07:30:00”, “08:00:00”, “08:30:00”, “09:00:00”, “09:30:00”, “10:00:00”, “10:30:00”, “11:00:00”, “11:30:00”, “12:00:00”]

获取两个日期之间的每一天

function formatEveryDay(start, end) {
    let dateList = []; 
    var startTime = getDate(start);
    var endTime = getDate(end);

    while ((endTime.getTime() - startTime.getTime()) >= 0) {
        var year = startTime.getFullYear();
        var month = startTime.getMonth() + 1 < 10 ? '0' + (startTime.getMonth() + 1) : startTime.getMonth() + 1;
        var day = startTime.getDate().toString().length == 1 ? "0" + startTime.getDate() : startTime.getDate();
        dateList.push(year + "-" + month + "-" + day); 
        startTime.setDate(startTime.getDate() + 1);
    }
    return dateList;
}


function getDate(datestr) {
    var temp = datestr.split("-");
    var date = new Date(temp[0], temp[1] - 1, temp[2]);
    return date;
}

例如:

formatEveryDay('2019-03-05','2019-03-16');

输出:

[“2019-03-05”, “2019-03-06”, “2019-03-07”, “2019-03-08”, “2019-03-09”, “2019-03-10”, “2019-03-11”, “2019-03-12”, “2019-03-13”, “2019-03-14”, “2019-03-15”, “2019-03-16”]

获取两个日期之间的所有月份

// 格式化时间,获取两个日期之间所有月份
function getMonthBetween(start, end) { //传入的格式YYYY-MM
    let dateList = []; // 时间格式 ‘2019-04-01’
    let dateList2 = []; // 时间格式 ‘2019-04’ 
    var s = start.split("-");
    var e = end.split("-");
    var min = new Date();
    var max = new Date();
    min.setFullYear(s[0], s[1] * 1 - 1, 1); // 开始日期
    max.setFullYear(e[0], e[1] * 1 - 1, 1); // 结束日期
    var current = min;
    while (current <= max) {
        var year = current.getFullYear();
        var month = current.getMonth() + 1 < 10 ? '0' + (current.getMonth() + 1) : current.getMonth() + 1;
        dateList.push(year + "-" + month + "-" + '01');
        dateList2.push(year + "-" + month); 
        current.setMonth(month);
    }
    return [dateList, dateList2];
}

例如:

getMonthBetween('2018-12-05','2019-03-16');

输出:

[[“2018-12-01”,“2019-01-01”,“2019-02-01”,“2019-03-01”], [“2018-12”,“2019-01”,“2019-02”,“2019-03”]]

获取最近n秒的时间

function formatDateToArray(steps = 40) {
    var nowDate = +new Date() - 10000;
    var xAxisDate = [],
        postDate = [];

    for (var i = 0; i < steps; i++) {
        var year = new Date(nowDate).getFullYear();
        var month = new Date(nowDate).getMonth() + 1 < 10 ? '0' + (new Date(nowDate).getMonth() + 1) : new Date(nowDate).getMonth() + 1;
        var day = new Date(nowDate).getDate() < 10 ? '0' + new Date(nowDate).getDate() : new Date(nowDate).getDate();
        var hour = new Date(nowDate).getHours() < 10 ? '0' + new Date(nowDate).getHours() : new Date(nowDate).getHours();
        var minute = new Date(nowDate).getMinutes() < 10 ? '0' + new Date(nowDate).getMinutes() : new Date(nowDate).getMinutes();
        var second = new Date(nowDate).getSeconds() < 10 ? '0' + new Date(nowDate).getSeconds() : new Date(nowDate).getSeconds();

        xAxisDate.unshift(hour + ':' + minute + ':' + second);
        postDate.unshift(year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second);
        nowDate = nowDate - 1000;
    }

    return [xAxisDate, postDate];
}

例如:获取最近10秒:

formatDateToArray(10);

获取最近 n 天

function getRecentDays(num) {
    var today = new Date();
    var steps = today.getTime() + 1000 * 60 * 60 * 24 * num;
    today.setTime(steps);
    var yy = today.getFullYear();
    var mm = today.getMonth();
    var dd = today.getDate();
    mm = bindMonth(mm + 1);
    dd = doHandleMonth(dd);
    return yy + "-" + mm + "-" + dd;
}

function bindMonth(month) {
    var m = month;
    if (month.toString().length == 1) {
        m = "0" + month;
    }
    return m;
}

function doHandleMonth(month) {
    var m = month;
    if (month.toString().length == 1) {
        m = "0" + month;
    }
    return m;
}

例如,9天前:

getRecentDays(-9);

获取两个日期之间的天数

function getDateDiff(startDate, endDate) {
    var startTime = new Date(Date.parse(startDate.replace(/-/g,   "/"))).getTime();
    var endTime = new Date(Date.parse(endDate.replace(/-/g,   "/"))).getTime();
    var dates = Math.abs((startTime - endTime)) / (1000 * 60 * 60 * 24);
    return  dates;
}

例如:

getDateDiff('2019-05-30','2019-05-20')

输出:
10

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 你可以使用以下代码实现一个基本的电子时钟效果,并包括一个暂停按钮: HTML代码: ```html <div id="clock"></div> <button id="pause">暂停</button> ``` JavaScript代码: ```javascript var clock = document.getElementById('clock'); var pauseBtn = document.getElementById('pause'); var timer; // 获取当前时间并更新时钟显示 function updateClock() { var now = new Date(); var hours = now.getHours(); var minutes = now.getMinutes(); var seconds = now.getSeconds(); clock.textContent = hours + ':' + minutes + ':' + seconds; } // 开始计时器 function startTimer() { timer = setInterval(updateClock, 1000); } // 暂停计时器 function pauseTimer() { clearInterval(timer); } // 初始加载时启动计时器 startTimer(); // 点击暂停按钮暂停计时器 pauseBtn.addEventListener('click', function() { if (pauseBtn.textContent === '暂停') { pauseBtn.textContent = '继续'; pauseTimer(); } else { pauseBtn.textContent = '暂停'; startTimer(); } }); ``` 在上面的代码中,我们首先定义了 `clock` 和 `pauseBtn` 变量,分别表示时钟显示区域和暂停按钮。然后定义了 `updateClock` 函数,用于获取当前时间并更新时钟显示。接着定义了 `startTimer` 函数,用于启动计时器并每隔一秒钟调用 `updateClock` 函数更新时钟显示。然后定义了 `pauseTimer` 函数,用于暂停计时器。最后,在初始加载时启动计时器,并在点击暂停按钮时暂停或继续计时器。 ### 回答2: 要实现JavaScript的电子时钟效果,首先需要获取当前时间。可以使用Date对象来获取当前的小时、分钟和秒数,然后将它们显示在HTML文档中。 以下是实现电子时钟效果的代码: ```html <!DOCTYPE html> <html> <head> <title>电子时钟</title> <style> #clock { font-size: 48px; text-align: center; margin-top: 200px; } </style> </head> <body> <h1 id="clock">00:00:00</h1> <button onclick="pause()">暂停</button> <script> var clock = document.getElementById('clock'); // 获取当前时间并显示在时钟中 function displayTime() { var now = new Date(); var hours = now.getHours(); var minutes = now.getMinutes(); var seconds = now.getSeconds(); var timeString = hours.toString().padStart(2, '0') + ':' + minutes.toString().padStart(2, '0') + ':' + seconds.toString().padStart(2, '0'); clock.textContent = timeString; } // 每隔一秒更新时间 setInterval(displayTime, 1000); // 暂停按钮点击事件处理函数 function pause() { if (clock.style.animationPlayState === 'paused') { clock.style.animationPlayState = 'running'; } else { clock.style.animationPlayState = 'paused'; } } </script> </body> </html> ``` 以上代码首先定义一个`displayTime`函数,用于获取当前时间并显示在`h1`元素中。然后使用`setInterval`函数每隔一秒调用`displayTime`函数,实现实时时间的更新。 按钮的点击事件处理函数`pause`用于控制时钟的暂停和继续。通过切换`clock`元素的`animation-play-state`属性来实现暂停和继续效果。 希望以上代码能够满足您的需求。 ### 回答3: 实现JS电子时钟效果,可以按照以下步骤进行: 首先,在HTML文件中创建一个包含时钟的div,例如: ```html <div id="clock"></div> <button id="pause">暂停</button> ``` 然后,在JS文件中写入如下代码: ```javascript // 获取时钟和暂停按钮的DOM对象 var clock = document.getElementById("clock"); var pauseBtn = document.getElementById("pause"); // 创建一个函数来获取当前时间并更新时钟 function updateClock() { var currentTime = new Date(); var hours = currentTime.getHours(); var minutes = currentTime.getMinutes(); var seconds = currentTime.getSeconds(); // 格式化时间,确保在个位数前面加上0 if (hours < 10) { hours = "0" + hours; } if (minutes < 10) { minutes = "0" + minutes; } if (seconds < 10) { seconds = "0" + seconds; } // 更新时钟的文本内容 clock.innerHTML = hours + ":" + minutes + ":" + seconds; } // 每隔一秒执行一次updateClock函数 var intervalId = setInterval(updateClock, 1000); // 点击暂停按钮时停止时钟 pauseBtn.onclick = function() { clearInterval(intervalId); }; ``` 以上代码会实现一个具有电子时钟效果的页面,每隔一秒钟会自动获取当前时间并更新时钟的显示。同时,通过点击"暂停"按钮可以停止时钟的运行。 希望对您有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值