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

问题描述 投票:2回答:1

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

要做到这一点,我这样做:

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

我错过了什么 ?

iphone compare nsdate dayofweek weekday
1个回答
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()来获取当周的当前日期,而不是建立自己的日期。

© www.soinside.com 2019 - 2024. All rights reserved.