iPhone - 我怎么检查日期是星期一?

时间:2011-01-23 00:17:52

标签: iphone compare nsdate dayofweek weekday

我想找一个约会是星期一。

为此,我这样做:

#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不包含任何有用的东西(等于2147483647),

我也想知道在这种情况下,[calendar components:NSWeekdayCalendarUnit fromDate:retDate]的用途是什么呢?

我也发现这证实了这个过程: How to check what day of the week it is (i.e. Tues, Fri?) and compare two NSDates?

我错过了什么?

1 个答案:

答案 0 :(得分:4)

在这里,你可以通过整数运行并返回天数:7 =星期六,1 =太阳,2 =星期一......

目标C

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

SWIFT 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()来获取当周的当天

,而不是建立自己的日期。