rickyduck
rickyduck

Reputation: 4084

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.

Upvotes: 3

Views: 3949

Answers (3)

mplungjan
mplungjan

Reputation: 178413

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)

Upvotes: 6

Antony Scott
Antony Scott

Reputation: 21996

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);

Upvotes: 3

Gustav Barkefors
Gustav Barkefors

Reputation: 5086

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;
}

Upvotes: 1

Related Questions