Home > front end >  Show a specific day of the week based on today's date
Show a specific day of the week based on today's date

Time:10-04

Hi everyone I'm working with 'Calendar' and I'm trying to find the right way and an elegant way to get the Tuesday of the next week only if today's date is a Sunday or Monday.

For example, if today is Sunday I would like to show the next available date on the following Tuesday

For now I have done this but I wanted to know if there is a right and more elegant way (i don't know if using DateInterval would be better)

enum WeekdaysRef: Int { case Dom = 1, Lun, Mar, Mer, Gio, Ven, Sab }

extension Date {
    
     func startDate(using calendar: Calendar = .current) -> Date {
        
        let sunday = calendar.component(.weekday, from: self) == WeekdaysRef.Dom.rawValue
        let monday = calendar.component(.weekday, from: self) == WeekdaysRef.Lun.rawValue

        return sunday ? today(adding: 2) : Monday ? today(adding: 1) : self
    }

     func today(adding: Int, _ calendar: Calendar = .current) -> Date {
        calendar.date(byAdding: .day, value: adding, to: self)!
    }
}

CodePudding user response:

You don't need a custom enum for this, check if the week day is 1 or 2 and then return next Tuesday

func nextTuesday(after date: Date, using calendar: Calendar = .current) -> Date? {
    let weekday = calendar.component(.weekday, from: date)
    return weekday > 2 ? nil : calendar.date(byAdding: .day, value: weekday % 2   1, to: date)
}

Note that I use a standalone function here and return nil if the in date isn't Sunday or Monday but this could easily be changed to using self in an extension and/or returning self or the given date instead of nil

  • Related