我对 NSDate
NSDateFormatter
和 NSCalendar
做了很多研究,但无法找到一种方法来找到特定的一天月。
例如,
我想查找 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/