Skip to content

Instantly share code, notes, and snippets.

@BrandonLWhite
Created December 18, 2018 15:29
Show Gist options
  • Save BrandonLWhite/579bc2aec283aa7c0f55f410666dd178 to your computer and use it in GitHub Desktop.
Save BrandonLWhite/579bc2aec283aa7c0f55f410666dd178 to your computer and use it in GitHub Desktop.
function dayPartToMoment(dayPart) {
return moment(dayPart, 'HHmm');
}
function momentAtDayPart(moment, dayPart) {
return dayPartToMoment(dayPart).set({
year: moment.year(),
month: moment.month(),
date: moment.date()
});
}
function nextMomentAtDayPart(startMoment, dayPart) {
const nextMoment = momentAtDayPart(startMoment, dayPart);
if(nextMoment.isBefore(startMoment)) {
nextMoment.add( {day: 1} );
}
return nextMoment;
}
function dayPartsToMoments(fromMomentDate, day_parts) {
return day_parts.map(dayPart => {
fromMomentDate = nextMomentAtDayPart(fromMomentDate, dayPart);
return fromMomentDate;
});
}
function momentsAsRanges(moments) {
return moments.map((moment, idx) => {
const nextMoment = idx < moments.length - 1 ? moments[idx + 1] : moments[0].clone().add({ days: 1 });
return {
start: moment,
end: nextMoment
};
});
}
const day_parts = ['2200', '0200', '0700'];
const dayPartMoments = dayPartsToMoments(moment(), day_parts);
console.log(dayPartMoments);
const dayPartRanges = momentsAsRanges(dayPartMoments);
console.log(dayPartRanges);
console.log(dayPartsToMoments(moment(), ['1730', '2215', '0201', '0700']));
console.log(momentsAsRanges(dayPartsToMoments(moment(), ['0400'])));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment