Created
February 27, 2024 21:51
-
-
Save dejurin/2e388f2f5abd08f3addb3615538a6722 to your computer and use it in GitHub Desktop.
Generate Month Calendar by Luxon
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
import { Info, DateTime } from "luxon"; | |
function generateMonthCalendar(dt: DateTime, locale = "en-US") { | |
const startOfMonth = dt.startOf("month"); | |
// Prepare an array to fill in the calendar | |
const calendar = []; | |
for (let i = 0; i < startOfMonth.weekday - 1; i++) { | |
calendar.push(" "); | |
} | |
if (!dt.daysInMonth) return; | |
for (let day = 1; day <= dt.daysInMonth; day++) { | |
// Format the day to ensure single-digit days are properly padded | |
let dayString = | |
day === dt.day | |
? `[${day.toString().padStart(2)}]` | |
: day.toString().padStart(3); | |
if ( | |
day === dt.day + 1 && | |
!DateTime.local(dt.year, dt.month, dt.day).isWeekend | |
) { | |
dayString = dayString.slice(1); | |
} | |
calendar.push(dayString); | |
} | |
// Add padding at the end if needed to complete the final week | |
while (calendar.length % 7 !== 0) { | |
calendar.push(" "); | |
} | |
// Generate days of the week headers based on locale | |
const daysOfWeek = Info.weekdays("short", { locale }); | |
const header = daysOfWeek.map((day) => day.padStart(3, " ")).join(" "); | |
// Month and year title | |
const monthYearTitle = dt.setLocale(locale).toFormat("LLLL yyyy"); | |
// Print the calendar | |
let printedCalendar = monthYearTitle + "\n" + header + "\n"; | |
for (let i = 0; i < calendar.length; i += 7) { | |
printedCalendar += calendar.slice(i, i + 7).join(" ") + "\n"; | |
} | |
return printedCalendar.trim(); | |
} | |
export default generateMonthCalendar; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment