Dev01
Dev01

Reputation: 14159

How to round to the nearest date using JavaScript Date Object

How to round to the nearest date using JavaScript Date Object?

I have 2020-10-14T18:10:48.960Z and I want it a function that returns 2020-10-15T05:00:00.000Z which is the closest date in my timezone CST. Or if I give it 2020-10-14T16:10:48.960Z I want it to return 2020-10-14T05:00:00.000Z.

Upvotes: 0

Views: 675

Answers (3)

DonCarleone
DonCarleone

Reputation: 859

//this code will round to the nearest date

const roundToNearestDay = (date) => {
  let isPastNoon = date.getHours() >= 12
  if (isPastNoon)
    //if first parameter > 23, will increment date +1
    date.setHours(24,0,0,0)
  else
    date.setHours(0,0,0,0)
  return date
}

let nearestDay = roundToNearestDay(new Date())
console.log(nearestDay)

Upvotes: 0

RobG
RobG

Reputation: 147483

You can check the hour and if it's before 12, set to the time to 00:00:00. If it's 12 or after, set the time to 24:00:00, e.g.

let d = new Date();
d.setHours(d.getHours() < 12? 0 : 24, 0,0,0);

console.log(d.toISOString() + '\n' + d.toString());

Upvotes: 1

dave
dave

Reputation: 64695

The easiest way I can think of is to just add 12 hours to the date, then truncate the time portion. This has the effect of rounding to the nearest date (anything before noon just has the time truncated, anything after goes to the next day, then has the time truncated).

let d = new Date();
// add 12 hours to the date
d.setTime(d.getTime() + (12*60*60*1000));
// truncate the time
d.setHours(0,0,0,0);
console.log(d);

Upvotes: 2

Related Questions