iphone - 如何找到一个月的特定日期?

标签 iphone ios cocoa-touch

我对 NSDate NSDateFormatterNSCalendar 做了很多研究,但无法找到一种方法来找到特定的一天月。 例如, 我想查找 12 月的第二个星期一的日期 (10/12/2012)。我知道如何找到周数或月数,但不知道如何做。

谢谢。

最佳答案

    // Set start date of the month you want
    NSString *str = @"01 - 12 - 2012";
    NSDateFormatter *formatter1 = [[[NSDateFormatter alloc] init] autorelease];
    [formatter1 setDateFormat:@"dd - MM - yyyy"];
    NSDate *date = [formatter1 dateFromString:str];
    NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
    NSDateComponents *weekdayComponents = [gregorian components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:date];
    // Get the weekday with sunday as one
    NSInteger weekday = [weekdayComponents weekday];
    int weekNumber = 2;
    int dayOfweek = 2;
    int x = (7 - weekday) * (weekNumber - 1) + dayOfweek;
    // Add the no. of weeks - 1 or - 2 depending on the value of x.
    // Also Add 1 as the start date is 1st Dec.
    if(x < 7)
    {
        x += 7 * (weekNumber - 1) + 1;
    }
    else
    {
        x += 7 * (weekNumber - 2) + 1;
    }

关于iphone - 如何找到一个月的特定日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13619039/

相关文章:

iphone - Cocoa/iPhone 中类似 Photoshop 的范围选择栏

iphone - 算法:Cocoa Touch 中的数组数组(可能使用 NSCountedSet)

iphone - 如何在 jQTouch 应用程序中要求全屏模式?

ios - iOS 7 中的唯一标识符

ios - 从后台激活 iOS 应用程序的快速机制

ios - 存档 iOS 应用程序时出错 - "generic specialization <Swift.String> of Swift.String.init"

ios - 从API加载图像

iphone - 有什么方法可以访问 objective c 运行时中任何类的私有(private)实例变量的地址吗?

javascript - Phonegap - Xcode 中的 Javascript 调试

iphone - _iVar 与 iVar_ 变量命名