我想测试一下今天是不是每个月的第一个星期一。我正在这样做:
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDate *today = [NSDate date];
NSInteger weekdayOfDate = [gregorianCalendar ordinalityOfUnit:NSWeekdayCalendarUnit inUnit:NSWeekCalendarUnit forDate:today];
if (weekdayOfDate == 2)
{
// Monday
}
但是这个代码在每个月的每个星期一都是正确的。我怎样才能得到每月的第一个星期一?
您需要添加条件检查我们当前是否在该月的前 7 天。但是,还请注意,从 iOS8 开始,您使用的某些值已被弃用。我添加了完整版本的代码,包括对已弃用值的替换:
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDate *today = [NSDate date];
NSInteger weekdayOfDate = [gregorianCalendar ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitWeekOfYear forDate:today];
NSInteger dayOfMonth = [gregorianCalendar ordinalityOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:today];
if (weekdayOfDate == 2 && dayOfMonth <= 7)
{
// This is the first Monday of this month
}
关于ios - 获取本月的第一个星期一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32201144/
欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) | Powered by Discuz! X3.4 |