开发者

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

开发者 https://www.devze.com 2023-02-06 18:41 出处:网络
I\'m trying to find if a date is Monday. To do this I proceed this way : #define kDateAndHourUnitsComponents NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMin

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 ?开发者_开发知识库


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

0

精彩评论

暂无评论...
验证码 换一张
取 消