2

我正在尝试查找日期是否为星期一。

为此,我以这种方式进行:

#define kDateAndHourUnitsComponents NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];

// for test and debug purpose
NSDateComponents* b = [calendar components:kDateAndHourUnitsComponents fromDate:retDate];
int a=[[calendar components:kDateAndHourUnitsComponents fromDate:theDate] weekday];
// -----------

if ([[calendar components:kDateAndHourUnitsComponents fromDate:theDate] weekday] == EKMonday) DoThis....

但这不起作用...... a 和 b 不包含任何有用的东西(a 等于 2147483647),

我也想知道[calendar components:NSWeekdayCalendarUnit fromDate:retDate]在这种情况下,它的用途是什么,不再有用了......

我还发现这证实了这个过程: 如何检查星期几(即周二、周五?)并比较两个 NSDate?

我错过了什么 ?

4

1 回答 1

4

来吧,这有效并通过整数返回天数:7 = Sat,1 = Sun,2 = Mon ...

目标 C

NSDate* curDate = [NSDate date];
int dayInt = [[[NSCalendar currentCalendar] components: NSWeekdayCalendarUnit fromDate: curDate] weekday];

斯威夫特 4.2

建立您想要检查星期几的日期

let dateComponents = DateComponents(
    year: 2019,
    month: 2 /*FEB*/,
    day: 23 /*23rd day of that month */
)

获取当前日历。

let cal = Calendar.current

现在使用日历检查构建日期是否为有效日期

guard let date = cal.date(from: dateComponents ) else {
    // The date you build up wasn't a valid day on the calendar
    return
}

//Now that your date is validated, get the day of the week

let weekdayIndex = cal.component(.weekday, from: date)

您会注意到“weekdayIndex”是一个整数。如果你想把它变成一个字符串,你可以这样做:

if let weekdayName = DateFormatter().weekdaySymbols?[ weekdayIndex - 1] {
    print("The weekday for your date is :: \(weekdayName)")
}

当然,您可以使用而不是建立自己的日期let date = Date()来获取当前星期几

于 2011-01-23T00:27:11.370 回答