最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】JS中获取当前时间之前或之后几个小时的时间

JS crifan 3284浏览 0评论

搜:

js date sub hour

参考:

javascript – How to subtract 2 hours from user’s local time? – Stack Overflow

How do I subtract minutes from a date in javascript? – Stack Overflow

datetime – Adding hours to Javascript Date object? – Stack Overflow

去试试

  let curAlarmDate = timestampToDate(current_date);
  console.log(`curAlarmDate=${curAlarmDate}`);
  let tmpPrevDate = curAlarmDate;
  let tmpNextDate = curAlarmDate;
  let preFiveHoursDate = tmpPrevDate.setHours(tmpPrevDate.getHours() – 5);
  let nexSevenHoursDate = tmpNextDate.setHours(tmpPrevDate.getHours() + 7);
  console.log(`preFiveHoursDate=${preFiveHoursDate},nexSevenHoursDate=${nexSevenHoursDate}`);

另外,再去把date转换为时间戳。

对于上述的内容,不够好,没有集成到Date对象中,自带此功能。

【总结】

最后改为:

// 对Date的扩展,返回之前或之后的多少个小时的时间
// 例子:
// (new Date()).prevNextHours(5) /  (new Date()).prevNextHours(-7)
// ==>
// current date [Tue Jun 06 2017 08:00:00 GMT+0800 (CST)] + [7] hours -> [Tue Jun 06 2017 15:00:00 GMT+0800 (CST)]
Date.prototype.prevNextHours = function (hoursNumber) {
  console.log(`Date prevNextHours: this=${this}, hoursNumber=${hoursNumber}`);
  // Note: here only got date pointer(reference) not date value, so later setHours will change this !!!
  // let tmpDate = this;
  let tmpDate = new Date(this);
  let changedDateTimestamp = tmpDate.setHours(tmpDate.getHours() + hoursNumber);
  console.log(`changedDateTimestamp=${changedDateTimestamp}`);
  let changedDate = new Date(changedDateTimestamp);
  console.log(`current date [${this}] + [${hoursNumber}] hours -> [${changedDate}]`);
  return changedDate;
};

调用:

  let curAlarmDate = timestampToDate(current_date);
  console.log(`current_date=${current_date} -> curAlarmDate=${curAlarmDate}`);
  // let tmpPrevDate = curAlarmDate;
  // let tmpNextDate = curAlarmDate;
  // let preFiveHoursDate = tmpPrevDate.setHours(tmpPrevDate.getHours() – 5);
  // let nexSevenHoursDate = tmpNextDate.setHours(tmpPrevDate.getHours() + 7);
  let preFiveHoursDate = curAlarmDate.prevNextHours(-5);
  let nexSevenHoursDate = curAlarmDate.prevNextHours(+7);
  console.log(`preFiveHoursDate=${preFiveHoursDate},nexSevenHoursDate=${nexSevenHoursDate}`);

效果:

Date prevNextHours: this=Tue Jun 06 2017 08:00:00 GMT+0800 (CST), hoursNumber=7
VM10267:65 changedDateTimestamp=1496732400000
VM10267:68 current date [Tue Jun 06 2017 08:00:00 GMT+0800 (CST)] + [7] hours -> [Tue Jun 06 2017 15:00:00 GMT+0800 (CST)]
index.js?7def:469 preFiveHoursDate=Tue Jun 06 2017 03:00:00 GMT+0800 (CST),nexSevenHoursDate=Tue Jun 06 2017 15:00:00 GMT+0800 (CST)

转载请注明:在路上 » 【已解决】JS中获取当前时间之前或之后几个小时的时间

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
89 queries in 0.189 seconds, using 22.06MB memory