Ghost
Ghost

Reputation: 326

round time to previous 15 min javascript

i want to get the prvious round 15 minutes from a given time or date in js for example i have 11:20 i want to get 11:15 , 12:57 i want to get 12:45 , i tried this :

      var round = 1000 * 60 * 15;
      var date = new Date()
      console.log(date)
      var rounded = new Date(Math.round(date.getTime() / round) * round)

but this give me the nearest 15 minutes not the previous , for 15:57 for example it give me 16:00 when i want to get 15:45 any solution ?

Upvotes: 3

Views: 1847

Answers (2)

Mohit Bhardwaj
Mohit Bhardwaj

Reputation: 10093

You need to use Math.floor instead of Math.round (as mentioned by @ciekals in comments) if you want to get the previous time.

Math.round will give the next 15 mins time if the time is closer to it e.g. 7:29 will give 7:30 if you use Math.round. But if you want 7:29 to return 7:15, then you should use Math.floor.

 var round = 1000 * 60 * 15;
var date = new Date()
console.log(date)
var rounded = new Date(Math.floor(date.getTime() / round) * round)
console.log(rounded)

Upvotes: 2

Martin Meli
Martin Meli

Reputation: 575

you can use modulus to round down

var rounded = new Date(date.getTime()-(date.getTime()%round)))

this way you remove the amount by which date differs from being a multiple of round

Upvotes: 0

Related Questions