检测NSDate是否包含周末 [英] Detecting if NSDate contains a weekend day

查看:73
本文介绍了检测NSDate是否包含周末的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将此类别添加到NSDate:

I have this category added to NSDate:

- (bool)isWeekend
{
  NSString* s = [self asString:@"e"];

  if ([s isEqual:@"6"])
    return YES;
  else if ([s isEqual:@"7"])
    return YES;
  else 
    return NO;
}

助手功能:

- (NSString*)asString:(NSString*)format
{
  NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  [dateFormatter setDateFormat:format];
  NSString *formattedDateString = [dateFormatter stringFromDate:self];
  [dateFormatter release];

  return formattedDateString;
}

如果

isWeekend是星期六或星期日,则应返回YES.但是,如果语言环境在星期日开始一周,则无法正常工作,在这种情况下,星期五将是第6天,而星期六将是第7天.

isWeekend should return YES if it is a saturday or a sunday. But it does not work if the locale has a week start on a sunday, in which case friday will be day 6 and saturday will be day 7.

我该如何解决?

推荐答案

您要使用NSCalendarNSDateComponents:

NSDate *aDate = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSRange weekdayRange = [calendar maximumRangeOfUnit:NSWeekdayCalendarUnit];
NSDateComponents *components = [calendar components:NSWeekdayCalendarUnit fromDate:aDate];
NSUInteger weekdayOfDate = [components weekday];

if (weekdayOfDate == weekdayRange.location || weekdayOfDate == weekdayRange.length) {
  //the date falls somewhere on the first or last days of the week
  NSLog(@"weekend!");
}

这是在假设一周的第一天和最后一天包含周末"的情况下进行的(对于公历是正确的.在其他日历中可能并非如此).

This is operating under the assumption that the first and last days of the week comprise the "week ends" (which is true for the Gregorian calendar. It may not be true in other calendars).

这篇关于检测NSDate是否包含周末的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆