JSFiddle - React, Tailwind, and code Playground
by Geoffrey Gazet
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
JavaScript
const oldDate = moment('2018-07-22T23:35:00Z');
const newDate = moment('2018-07-25T21:05:00Z');
const compare = Math.round((newDate - oldDate) / 1000 / 60); // minutes
const modulo = compare % 30;
let newFormatedDate = null;
console.log('compare, modulo', newDate.format('X'), compare, modulo);
if (Math.abs(modulo) <= 15) {
newFormatedDate = Number(newDate.format('X')) - Number(modulo * 60);
} else {
let restToRound = Number((30 - Math.abs(modulo)) * 60);
if (modulo < 0) {
restToRound = restToRound * - 1;
}
newFormatedDate = Number(newDate.format('X')) + restToRound;
}
const newFormatedDateMoment = moment.unix(newFormatedDate);
console.log(newFormatedDateMoment.format('YYYY-MM-DD HH:mm'));