Home > Blockchain >  Javascript round date to nearest full date
Javascript round date to nearest full date

Time:11-12

I have dates in different formats like these:

2022-03-13T23:00:00.000Z
1647817200000

I want to round the date to the nearest date basically

2022-03-13T23:00:00.000Z should be 2022-03-14T00:00:00.000Z

and something like 2022-03-14T01:00:00.000Z should be 2022-03-14T00:00:00.000Z

CodePudding user response:

The general rule for rounding is Math.round(N/x)*x where N is a number you want to round and x is what you want to round to.

As Date.valueOf() returns a number of milliseconds you can simply round that to the number of milliseconds in a day.

const OneDay = 86400000
const roundToNearestDay = d => new Date((Math.round(d.valueOf()/OneDay)*OneDay));

const morning = new Date("2022-03-13T11:00:00.000Z");
const evening = new Date("2022-03-13T23:00:00.000Z")

console.log(roundToNearestDay(morning))
console.log(roundToNearestDay(evening))
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related