js 在一个日期上面加上指定时间(几小时、几分钟、几秒)

您所在的位置:网站首页 半天等于多少小时 js 在一个日期上面加上指定时间(几小时、几分钟、几秒)

js 在一个日期上面加上指定时间(几小时、几分钟、几秒)

2024-01-21 12:44| 来源: 网络整理| 查看: 265

    在前端开发时,有时我们需要在 javascript 中对日期加上或减去指定的时间。本文简单记录如何对js日期加上或减去指定的时间。

    一、使用js标准日期对象

    当使用js日期对象Date进行时间加减时,这个处理相对比较简单,直接调用Date对象的方法进行操作。只是Date对象最后需要进行格式化(格式化可以参考这篇文章“js 常用日期字符串和日期转换 ”),这样显示比较友好。

    示例代码如下:

var curTime = new Date(); // curTime: Tue Oct 13 2020 16:44:47 GMT+0800 (中国标准时间) console.log('curTime:', curTime); // 1. 加上1个小时 var addHour = curTime.setHours(curTime.getHours() + 1); // addHour: 1602582287529 console.log('addHour:', addHour); // Tue Oct 13 2020 17:44:47 GMT+0800 (中国标准时间) console.log(new Date(addHour)); // 2. 在当前时间curTime变量上加上10分钟 var addMinute = new Date(curTime.setMinutes(curTime.getMinutes() + 10)); // addMinute: Tue Oct 13 2020 17:54:47 GMT+0800 (中国标准时间) console.log('addMinute:', addMinute); // 3. 在当前时间curTime变量上加上1分40秒(100秒) var addSeconds = new Date(curTime.setSeconds(curTime.getSeconds() + 100)); // addSeconds: Tue Oct 13 2020 17:56:27 GMT+0800 (中国标准时间) console.log('addSeconds:', addSeconds);

    二、使用字符串格式日期

    使用字符串日期的处理,首先需要将字符串转换为js的Date对象。后续的处理,和第一步相同。

    代码如下:

var rawdate = stringToDate('2020-10-13 12:00:01'); // 日期加上11秒 var addSecond = 11; var resDate = new Date(rawdate.setSeconds(rawdate.getSeconds() + addSecond)); var res = format(resDate, "yyyy-MM-dd hh:mm:ss"); console.log(res); // js字符串转日期Date // 字符串格式:2020-10-13 12:00:01 function stringToDate(strDate) {     var tempStrs = strDate.split(" ");     var dateStrs = tempStrs[0].split("-");     var year = parseInt(dateStrs[0], 10);     var month = parseInt(dateStrs[1], 10) - 1;     var day = parseInt(dateStrs[2], 10);     var timeStrs = tempStrs[1].split(":");     var hour = parseInt(timeStrs [0], 10);     var minute = parseInt(timeStrs[1], 10);     var second = parseInt(timeStrs[2], 10);     var date = new Date(year, month, day, hour, minute, second);     return date; } // js日期Date格式化为字符串 // 字符串格式:2020-10-13 12:00:01 function format(date, fmt) {     var o = {         "M+": date.getMonth() + 1, //月份         "d+": date.getDate(), //日         "h+": date.getHours(), //小时         "m+": date.getMinutes(), //分         "s+": date.getSeconds(), //秒         "q+": Math.floor((date.getMonth() + 3) / 3), //季度         "S": date.getMilliseconds() //毫秒     };     if (/(y+)/.test(fmt)) {         fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));     }     for (var k in o) {         if (new RegExp("(" + k + ")").test(fmt)) {             fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ?                 (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));         }     }     return fmt; }


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3