Round moment.js object time to nearest 30 minute interval

JavascriptMomentjs

Javascript Problem Overview


I was trying to round the moment.js time object to next nearest 30 minute interval. But looks my logic us wrong.

Ex:

10:13am -> 10:30am
11:45am -> 12:00pm

Here is my current code

start = moment();
minuteReminder = start.minute() % 30;
start.add(minuteReminder, 'minutes');
start.format("D YYYY, h:mm:ss a");

Javascript Solutions


Solution 1 - Javascript

Edit 2021 : easiest solution

const start = moment('2018-12-08 09:42');
const remainder = 30 - (start.minute() % 30);
 
const dateTime = moment(start).add(remainder, "minutes").format("DD.MM.YYYY, h:mm:ss a");

console.log(dateTime);

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>

Million ways to do this. You don't need moment.js really. Anyway, here is one.

Solution 2 - Javascript

Based on @Volune and @Cabloo answers and comments, an updated version can look like:

function round(date, duration, method) {
    return moment(Math[method]((+date) / (+duration)) * (+duration)); 
}

Which then can be used like:

var date = moment();
var roundedDate = round(date, moment.duration(15, "minutes"), "ceil");

Solution 3 - Javascript

A generic solution:

var ROUNDING = 30 * 60 * 1000; /*ms*/
start = moment();
start = moment(Math.ceil((+start) / ROUNDING) * ROUNDING);
start.format("D YYYY, h:mm:ss a");

You can change ROUNDING from 30 minutes to whatever you want, and change Math.ceil by Math.round or Math.floor if you want another way to round the value.

Solution 4 - Javascript

You can do it by a simple if-else clause:

if(moment().minute()> 30){
    var myTime = moment().minute(30).second(0);
} else {
    var myTime = moment().minute(0).second(0);
}

Solution 5 - Javascript

You could do it with two ifs:

// Current date
let now = moment();

// Getting hour and minute
let hour   = now.hour();
let minute = now.minute();

// Rounding minute on 30 mins interval
if(minute <= 30) now.set({minute: 30});
if(minute >  30) now.set({hour: hour + 1, minute: 0});

Solution 6 - Javascript

even though the question has been answered, I'd like to share my solution too.

var moment = require('moment');

const roundToNearestXXMinutes = (start, roundTo) => {
    let remainder = roundTo - (start.minute()+ start.second()/60) % roundTo;
    
    remainder = (remainder >  roundTo/2) ? remainder = -roundTo + remainder : remainder;
    const changedDate = moment(start).add(remainder, "minutes" ).seconds(0).format("DD.MM.YYYY HH:mm:ss");    
}

roundToNearestXXMinutes(moment(), 15);

EDIT: Thanks to Ishmael Sibisi for pointing to a flaw in my code! :)

Solution 7 - Javascript

For my case, I instead wanted something like

04-28-2021 20:00 => 04-28-2021 20:00
04-28-2021 20:30 => 04-28-2021 20:30
04-28-2021 20:11 => 04-28-2021 20:00
04-28-2021 20:35 => 04-28-2021 20:30

so the function below did the trick

function toNearest30Minutes(date) {
  const start = moment(date)
  let remainder: number
  const elapse = start.minute() % 30
  if (elapse === 0) {
    return moment(date).format()
  } else {
    remainder = 30 - elapse
    return moment(start).add(remainder, "minutes").format()
  }
}

The function above is just an adaptation of @jtromans answer higher above

Solution 8 - Javascript

One-line solution

 moment().add( moment().minute() > 30 && 1 , 'hours').minutes( moment().minute() <= 30 ? 30 : 0).format("hh:mm a")

Working exemple :

var min = moment().minute()
var dateTime = moment().add(min > 30 && 1 , 'hours').minutes(min <= 30 ? 30 : 0).format("hh:mm a")

console.log(dateTime);

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>

Solution 9 - Javascript

the code below rounds up the current time to the nearest 30 minutes and also flawlessly takes care of any trailing seconds

    var moment = require('moment')
    var main = Date.now() //2020-03-13T23:17:34+01:00
    var mainFormat = moment(main)
    var secs = mainFormat.second()
    var justMinutes = mainFormat.subtract(secs, 'seconds')
    var remainder = 30 - (justMinutes.minute() % 30);
    var dateTime = moment(justMinutes).add(remainder, 'minutes')
    var final = dateTime.format()
    console.log(final) 
    //2020-03-13T23:20:00+01:00

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAchintha SamindikaView Question on Stackoverflow
Solution 1 - JavascriptjtromansView Answer on Stackoverflow
Solution 2 - JavascriptjanhartmannView Answer on Stackoverflow
Solution 3 - JavascriptVoluneView Answer on Stackoverflow
Solution 4 - JavascriptAidaNowView Answer on Stackoverflow
Solution 5 - JavascriptErik Martín JordánView Answer on Stackoverflow
Solution 6 - JavascriptJosef Held - SatankoView Answer on Stackoverflow
Solution 7 - JavascriptSantersView Answer on Stackoverflow
Solution 8 - JavascriptcrgView Answer on Stackoverflow
Solution 9 - Javascriptbello hargbolaView Answer on Stackoverflow