研究了很久NSDate
,NSDateFormatter
和NSCalendar
,不知道怎麼實現找出一月個中指定一天的功能。比如查詢十二月第二個星期一的日期是多少,不知道怎麼實現呢?
謝謝指教。
謝謝回答者的答案,我根據得到的回答,實現了。最後這樣的
-(void)findWeekDay:(NSInteger)weekDay forWeek:(NSInteger)week OfMonth:(NSInteger)month OfYear:(NSInteger)year
{
NSDateComponents *dateComp = [[NSDateComponents alloc]init];
[dateComp setYear:year];
[dateComp setMonth:month];
[dateComp setDay:1];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *firstDate=[gregorian dateFromComponents:dateComp]; //Sets first date of month.
firstDate=[self dateToGMT:firstDate];
NSLog(@"First date: %@",firstDate);
NSDateComponents *dateComp1 = [gregorian components:NSDayCalendarUnit|NSWeekdayCalendarUnit fromDate:firstDate];
NSInteger firstWeekDay=[dateComp1 weekday]; //Gets firstday of a week. 1-Sunday, 2-Monday and so on.
NSLog(@"First Week Day: %d",firstWeekDay);
NSRange daysInMonth = [gregorian rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:firstDate]; //To get number of days in that month
NSInteger x; //days to be added to first date
if (firstWeekDay < weekDay) {
x = (weekDay - firstWeekDay) + (7 * (week-1));
}
if (firstWeekDay > weekDay) {
x = (7 - firstWeekDay + weekDay) + (7 * (week-1));
}
if (firstWeekDay == weekDay) {
x = (7 * (week-1));
}
if (x > daysInMonth.length) {
NSLog(@"Invalid Date: %d",x);
}
else {
NSLog(@"Days to be added: %d",x);
NSDateComponents *dateComp2 = [[NSDateComponents alloc]init];
[dateComp2 setYear:0];
[dateComp2 setMonth:0];
[dateComp2 setDay:x];
NSDate *desiredDate = [gregorian dateByAddingComponents:dateComp2 toDate:firstDate options:0];
NSLog(@"Your desired date is: %@",desiredDate);
}
}
- (NSDate *)dateToGMT:(NSDate *)sourceDate {
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSDate* destinationDate = [[NSDate alloc] initWithTimeInterval:destinationGMTOffset sinceDate:sourceDate];
return destinationDate;
}
現在如果查詢十二月的第三個星期一調用方法:
[self findWeekDay:2 forWeek:3 OfMonth:12 OfYear:2012];