Last active
May 30, 2024 20:12
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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