1

My function returns the time like this 10:43:22 for example. How can I round the time to the closest minute so 10:43:22 becomes 10:43 and 10:43:44 becomes 10:44.

function time (){
    let date = new Date()
    let time = date.toLocaleTimeString("it-IT");
}
  • 3
    Does this answer your question? [Round a Date() to the nearest 5 minutes in javascript](https://stackoverflow.com/questions/10789384/round-a-date-to-the-nearest-5-minutes-in-javascript) it's for 5 minutes but you can easily change that – Cjmarkham Apr 15 '21 at 15:21
  • 1
    you use a datetime formatter. Also, remember to ask yourself whether what you want makes sense. Just "not showing seconds" is almost _always_ fine because when it comes to time, it's not "10:44" until it's been more than "10:43:59". Time does not generally "round up". – Mike 'Pomax' Kamermans Apr 15 '21 at 15:21

3 Answers3

2

I would get the milliseconds of that date and then round that value to minutes (1 minute = 60,000 milliseconds).

function createRoundedDate(date) {
  var ts = date.getTime();
  ts = Math.round(ts / 60000) * 60000;
  return new Date(ts);
}

console.log(createRoundedDate(new Date()))
Cjmarkham
  • 9,484
  • 5
  • 48
  • 81
Iván Pérez
  • 2,278
  • 1
  • 24
  • 49
  • 1
    Adding `.toLocaleTimeString("it-IT",{hour:'numeric',minute:'2-digit'})` would finish the job. :-) – RobG Apr 16 '21 at 01:22
0

we can use the below code to create the new Date by removing the seconds part

var d = new Date()
var d1 = new Date(d.getYear(),d.getMonth(),d.getDate(),d.getHours(),d.getMinutes())
console.log(d1.toLocaleTimeString('it-IT'))
Test12345
  • 1,625
  • 1
  • 12
  • 21
0

This should do it, and handle going over hours etc. (60,000 ticks is 1 min)

function time(){
  let date = new Date()
  let dateMins = new Date(date.getYear(),date.getMonth(),date.getDay(),date.getHours(),date.getMinutes())
  let roundedDate = new Date(dateMins.getTime() + date.getSeconds() > 30 ? 60000 : 0 )
  let time = roundedDate.toLocaleTimeString("it-IT");
}