Skip to content

Instantly share code, notes, and snippets.

@lucivaldo
Last active May 30, 2024 20:12
Show Gist options
  • Save lucivaldo/9fabb52a8fc636b711b9b067f20929f6 to your computer and use it in GitHub Desktop.
Save lucivaldo/9fabb52a8fc636b711b9b067f20929f6 to your computer and use it in GitHub Desktop.
Função Typescript para gerar um intervalo de objetos Date Javascript para ser utilizado na construção de calendários de meses
const makeDate = (year: number, month: number, day: number) =>
new Date(year, month, day, 0, 0, 0)
const makeRangeBetweenDates = (start: Date, end: Date) => {
const range: Date[] = []
for (
const i = new Date(start);
i.getTime() <= end.getTime();
i.setDate(i.getDate() + 1)
) {
range.push(new Date(i))
}
return range
}
export function getMonthBehavior(date?: Date) {
const currentDate = date || new Date()
const firstDate = makeDate(
currentDate.getFullYear(),
currentDate.getMonth(),
1,
)
const lastDate = makeDate(
currentDate.getFullYear(),
currentDate.getMonth() + 1,
0,
)
const firstDateInRange = makeDate(
firstDate.getFullYear(),
firstDate.getMonth(),
-firstDate.getDay() + 1,
)
const lastDateInRange = makeDate(
lastDate.getFullYear(),
lastDate.getMonth(),
lastDate.getDate() + (7 - lastDate.getDay() - 1),
)
const range = makeRangeBetweenDates(firstDateInRange, lastDateInRange)
return {
currentDate,
firstDate,
firstDateInRange,
lastDate,
lastDateInRange,
range,
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment