JSFiddle - React, Tailwind, and code Playground
by Harm Zeinstra
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
JavaScript
function getRoundedUpToFiveMinutes(momentSubject) {
var momentValue = moment(momentSubject);
momentValue.seconds(0);
return momentValue.minutes(Math.ceil(momentValue.minutes() / 5) * 5);
}
let subjects = [{
current: moment('2020-04-06 14:04:32'),
parsed: moment('2020-04-06 14:05')
},
{
current: moment('2020-04-06 14:01'),
parsed: moment('2020-04-06 14:05')
},
{
current: moment('2020-04-06 14:06:57'),
parsed: moment('2020-04-06 14:10')
},
{
current: moment('2020-04-06 14:57:57'),
parsed: moment('2020-04-06 15:00')
},
{
current: moment('2020-04-06 00:00:00'),
parsed: moment('2020-04-06 00:00:00')
},
{
current: moment('2020-04-06 00:00:1'),
parsed: moment('2020-04-06 00:00:00')
},
{
current: moment('2020-04-06 00:01:1'),
parsed: moment('2020-04-06 00:05:00')
},
{
current: moment('2020-04-06 23:59:10'),
parsed: moment('2020-04-07 00:00:00')
},
{
current: moment('2020-12-31 23:59:10'),
parsed: moment('2021-01-01 00:00:00')
},
{
current: moment('2020-02-28 23:59:10'), // not leap
parsed: moment('2020-02-29 00:00:00')
},
{
current: moment('2019-02-28 23:59:10'), // leap
parsed: moment('2019-03-01 00:00:00')
}
]
// clear output is good output
console.clear();
let color = 'green';
subjects.forEach(subject => {
let output = getRoundedUpToFiveMinutes(subject.current);
if (!output.isSame(subject.parsed)) {
color = 'red';
console.error(output.format('DD-MM-YYYY HH:mm:ss') +
' :: is not the same as :: ' +
subject.parsed.format('DD-MM-YYYY HH:mm:ss'))
}
});
document.getElementsByTagName('body')[0].style.backgroundColor = color;