Version casi lista
This commit is contained in:
@@ -0,0 +1,84 @@
|
||||
import Foundation
|
||||
|
||||
extension Date {
|
||||
func addingDays(_ days: Int) -> Date {
|
||||
Calendar.current.date(byAdding: .day, value: days, to: self)!
|
||||
}
|
||||
|
||||
func addingMinutes(_ minutes: Int) -> Date {
|
||||
Calendar.current.date(byAdding: .minute, value: minutes, to: self)!
|
||||
}
|
||||
|
||||
func startOfWeek() -> Date {
|
||||
let calendar = Calendar.current
|
||||
var cal = calendar
|
||||
cal.firstWeekday = 2 // Monday
|
||||
let components = cal.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)
|
||||
return cal.date(from: components) ?? self
|
||||
}
|
||||
|
||||
func dayOfWeekIndex() -> Int {
|
||||
let calendar = Calendar.current
|
||||
let weekday = calendar.component(.weekday, from: self)
|
||||
// Convert to 0=Monday format
|
||||
return (weekday + 5) % 7
|
||||
}
|
||||
|
||||
var isToday: Bool {
|
||||
Calendar.current.isDateInToday(self)
|
||||
}
|
||||
|
||||
var isPast: Bool {
|
||||
self < Calendar.current.startOfDay(for: Date())
|
||||
}
|
||||
|
||||
func formattedWeekRange() -> String {
|
||||
let endDate = self.addingDays(6)
|
||||
let formatter = DateFormatter()
|
||||
formatter.locale = Locale.current
|
||||
|
||||
let dayFormatter = DateFormatter()
|
||||
dayFormatter.dateFormat = "d"
|
||||
|
||||
let monthFormatter = DateFormatter()
|
||||
monthFormatter.dateFormat = "MMM"
|
||||
|
||||
let startDay = dayFormatter.string(from: self)
|
||||
let endDay = dayFormatter.string(from: endDate)
|
||||
let month = monthFormatter.string(from: endDate)
|
||||
|
||||
return "\(startDay)-\(endDay) \(month)"
|
||||
}
|
||||
|
||||
func startOfMonth() -> Date {
|
||||
let calendar = Calendar.current
|
||||
let components = calendar.dateComponents([.year, .month], from: self)
|
||||
return calendar.date(from: components) ?? self
|
||||
}
|
||||
|
||||
func addingMonths(_ months: Int) -> Date {
|
||||
Calendar.current.date(byAdding: .month, value: months, to: self) ?? self
|
||||
}
|
||||
|
||||
func monthYearLabel(locale: Locale = .current) -> String {
|
||||
let formatter = DateFormatter()
|
||||
formatter.locale = locale
|
||||
formatter.setLocalizedDateFormatFromTemplate("LLLL yyyy")
|
||||
return formatter.string(from: self)
|
||||
}
|
||||
}
|
||||
|
||||
func combineDateAndTime(date: Date, time: Date) -> Date {
|
||||
let calendar = Calendar.current
|
||||
let dateComponents = calendar.dateComponents([.year, .month, .day], from: date)
|
||||
let timeComponents = calendar.dateComponents([.hour, .minute], from: time)
|
||||
|
||||
var combined = DateComponents()
|
||||
combined.year = dateComponents.year
|
||||
combined.month = dateComponents.month
|
||||
combined.day = dateComponents.day
|
||||
combined.hour = timeComponents.hour
|
||||
combined.minute = timeComponents.minute
|
||||
|
||||
return calendar.date(from: combined) ?? date
|
||||
}
|
||||
Reference in New Issue
Block a user