iPhone - how may I check if a date is Monday?

允我心安 提交于 2019-12-13 16:08:03

问题


I'm trying to find if a date is Monday.

To do this I proceed this way :

#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....

But this doesn't work... a and b does not contain anything useful (a equals 2147483647),

I also wonder what can be the use of [calendar components:NSWeekdayCalendarUnit fromDate:retDate] that is not useful anymore in that case...

I also found this that confirms the process : How to check what day of the week it is (i.e. Tues, Fri?) and compare two NSDates?

What did I miss ?


回答1:


Here ya go, this works and returns days via ints: 7 = Sat, 1 = Sun, 2 = Mon...

OBJECTIVE C

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

SWIFT 4.2

Build up the date you want to check what day of the week it is

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

get the current calendar.

let cal = Calendar.current

now use the calendar to check if the build up date is a valid date

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)

You'll notice that the 'weekdayIndex' is an integer. If you want to make it a string, you can do something like this:

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

Instead of building your own date, you are of course allowed to use let date = Date() instead to get what the current day of the week is



来源:https://stackoverflow.com/questions/4771511/iphone-how-may-i-check-if-a-date-is-monday

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!