// // Date+Extension.swift // VDS // // Created by Kanamarlapudi, Vasavi on 26/04/24. // import Foundation extension Date { static var firstDayOfWeek = Calendar.current.firstWeekday /// Capitalizes the first letter of the day of the week static var capitalizedFirstLettersOfWeekdays: [String] { let calendar = Calendar.current let weekdays = calendar.shortWeekdaySymbols return weekdays.map { weekday in guard let firstLetter = weekday.first else { return "" } return String(firstLetter).capitalized } } /// Returns all month names static var fullMonthNames: [String] { let dateFormatter = DateFormatter() dateFormatter.locale = Locale.current return (1...12).compactMap { month in dateFormatter.setLocalizedDateFormatFromTemplate("MMMM") let date = Calendar.current.date(from: DateComponents(year: 2000, month: month, day: 1)) return date.map { dateFormatter.string(from: $0) } } } var startOfMonth: Date { Calendar.current.dateInterval(of: .month, for: self)!.start } var endOfMonth: Date { let lastDay = Calendar.current.dateInterval(of: .month, for: self)!.end return Calendar.current.date(byAdding: .day, value: -1, to: lastDay)! } /// Get the number of days of the month var numberOfDaysInMonth: Int { Calendar.current.component(.day, from: endOfMonth) } var firstWeekDayBeforeStart: Date { let startOfMonthWeekday = Calendar.current.component(.weekday, from: startOfMonth) var numberFromPreviousMonth = startOfMonthWeekday - Self.firstDayOfWeek if numberFromPreviousMonth < 0 { numberFromPreviousMonth += 7 // Adjust to a 0-6 range if negative } return Calendar.current.date(byAdding: .day, value: -numberFromPreviousMonth, to: startOfMonth)! } /// Get the days of the month to display var calendarDisplayDays: [Date] { var days: [Date] = [] // Start with days from the previous month to fill the grid let firstDisplayDay = firstWeekDayBeforeStart var day = firstDisplayDay while day < startOfMonth { days.append(day) day = Calendar.current.date(byAdding: .day, value: 1, to: day)! } // Add days of the current month for dayOffset in 0.. Bool { return date1.compare(self) == self.compare(date2) } /// Returns the month name of the given date func getMonthName(date: Date) -> String { let names = Date.fullMonthNames return names[date.monthInt - 1] } }