【问题标题】:Get the date of next saturday in Objective-C?在Objective-C中获取下周六的日期?
【发布时间】:2011-06-02 12:46:47
【问题描述】:

在 iOS 的 Objective-C 中如何获得今天之后的第一个星期六的日期?

【问题讨论】:

标签: iphone objective-c ios nsdate


【解决方案1】:
NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *date = [NSDate date];
NSDateComponents *weekdayComponents = [gregorian components:NSWeekdayCalendarUnit fromDate:date];
NSInteger todayWeekday = [weekdayComponents weekday];

enum Weeks {
    SUNDAY = 1,
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY
};

NSInteger moveDays=SATURDAY-todayWeekday;
if (moveDays<=0) {
    moveDays+=7;
}

NSDateComponents *components = [NSDateComponents new];
components.day=moveDays;

NSCalendar *calendar=[[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDate* newDate = [calendar dateByAddingComponents:components toDate:date options:0];

NSLog(@"%@",newDate);

【讨论】:

    【解决方案2】:

    [NSDate dateWithNaturalLanguageString: @"next Saturday"]


    编辑:从 OS X 10.9 和 iOS 8 开始,您可以这样做:

    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    NSDate *now = [NSDate date];
    NSDateComponents *saturday = [[NSDateComponents alloc] init];
    saturday.weekday = 7 /* Saturday */;
    
    NSDate *nextSaturday = [calendar nextDateAfterDate:now matchingComponents:saturday options:0];
    

    【讨论】:

    • 来自官方文档:此方法 (dateWithNaturalLanguageString:) 仅支持一组有限的口语短语,主要是英语。它可能会产生意想不到的结果,强烈建议不要使用它。
    • @Bavarious - 我确实看到了。这比我打算做的要简单得多,而且它适用于我的情况。
    • 即使它只支持一组有限的英语口语短语,“下周六”也适用于任何应用程序。
    • 如果它实际上在 iOS SDK 中但不在文档中,那么我希望它会被应用审查团队视为私有 API,因此您将无法进入应用商店。你也真的在设备上运行过它吗?它可能实际上并不存在,并且模拟器正在使用 OS X 实现。
    • 这仅适用于 OS X,已在 10.10 中弃用。
    【解决方案3】:

    这将指导您完成处理日历日期的过程:

    Calendrical Calculations

    【讨论】:

      猜你喜欢
      • 2018-02-04
      • 1970-01-01
      • 2018-05-31
      • 1970-01-01
      • 1970-01-01
      • 2021-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多