-2

Rounding to the nearest 15 minute interval. I was wondering if there is a way for me to round up or down to the last nearest 15 minute interval. i use this function but beetween H and H=15 minutes, i haven't no argument.

var now = new Date();
var year = now.getFullYear();
var hour = ("0" + now.getUTCHours()).slice(-2);
var day = ("0" + now.getDate()).slice(-2);
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var minutes = ("0" + now.getMinutes()).slice(-2);

var imageUrl = 'image/type'+month+''+day+'.'+hour+''+minutes+'.png',
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
La jenny
  • 1
  • 2
  • 2
    Took no more than typing “javascript round minutes to 15” into Google to find that, so next time please make a proper research effort before asking. – CBroe Jun 22 '18 at 12:05

1 Answers1

0

To round down:

var d = new Date('2001-02-03T04:59:59.999Z'), rounded = new Date( d - d % 9e5 );

console.log( d ); console.log( rounded );        /* 1000 ms * 60 sec * 15 min = 900000 */

console.log( rounded.toJSON().replace(/.*-(..)-(..)T(..):(..).*/, 'image/type$1$2$3$4.png') );

To round to nearest 15 minutes:

var d = new Date('2001-02-03T04:52:30.000Z'), 
    rounded = new Date( Math.round(d / 9e5) * 9e5 );

console.log( d ); console.log( rounded );       
Slai
  • 22,144
  • 5
  • 45
  • 53