如何使用 Swift 中的 NSDate 检查一周中的特定日期?

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

使用 NSDate 和 Swift,我想制作一个 if 语句,在一周中的特定一天触发。

具体来说,当今天是星期一时,名为 labelone 的标签的文本应该是 "Have a nice week",而当它是任何其他日期时 labelone 应该被隐藏。

我知道更改标签中的文本并将其隐藏的代码,但是如何以这种方式使用 NSDate 构建 if 语句?

这是我试过的:

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")
}

有更好的方法吗?

使用 Calendar / NSCalendar 执行您的日历计算:

Swift 3 岁及以上

let today = Date()
let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents([.weekday], from: today)

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

Swift 2

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")
}

星期一、星期二等仅在公历中定义。有的,比如农历,根本就没有星期的概念。

这就是我完成任务的方式。

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)
}