开发者

How to get next 12:00:00PM in javascript date object

Just need to know how to get the closest 12:00:00pm in the JavaScript date object, for some reason I'm baffled! EG if it is 09:00AM on the 1st of July, then it will be 12:00PM 1st July, however if it's 01:00PM on the 1st of July, 开发者_如何转开发then I need 12:00PM 2nd July returning.

Cheers.


Like this: Add a day if hours > 12

var nextNoon = new Date();
if (nextNoon.getHours() >= 12) nextNoon.setDate(nextNoon.getDate() + 1)
nextNoon.setHours(12, 0, 0, 0)
console.log(nextNoon)


try this ...

var dt = new Date();
var tomorrowNoon = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate() + 1, 12, 0, 0);

I've checked it out for going past the end of the month and that works too ...

var dt = new Date(2011, 7, 31);
var tomorrowNoon = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate() + 1, 12, 0, 0);


JavaScript's Date is lenient in the sense that e.g. Aug 32 equals Sep 1, so something like this perhaps:

function getNextNoon() {
  var noon = new Date();
  if (noon.getHours() >= 12) {
    noon.setDate(noon.getDate() + 1);
  }
  noon.setHours(12);
  noon.setMinutes(0);
  return noon;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜