Search code examples
swiftnsdate

How can I check for a specific day of the week using NSDate in Swift?


Using NSDate and Swift, I want to make an if statement that triggers on a particular day of the week.

Specifically, when the current day is Monday the text of a label named labelone should be "Have a nice week" and when it's any other day labelone should be hidden.

I know the code to change the text from the label and make it hidden, but how can I structure an if statement using NSDate in this way?

This is what I've tried:

let today = NSDate()
let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
let components = calendar!.components([.Weekday], fromDate: today)

if components.weekday == 2 {
    print("Hello Monday")
} else {
    print("It's not Monday")
}

Is there a better way of doing it?


Solution

  • This is how I would accomplish the task.

    var CurrentDate = NSDate()
    let dateFormatter = NSDateFormatter()
    dateFormatter.timeZone = NSTimeZone()
    dateFormatter.dateFormat = "ccc"
    
    let Monday = dateFormatter.stringFromDate(CurrentDate)
    let isMonday = "Mon"
    if Monday == isMonday {
       print("It's Monday")
    }
    else {
       let otherDay = dateFormatter.stringFromDate(CurrentDate)
       print(otherDay)
    }