程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> ios-如何查詢一個月中特定的一天?

ios-如何查詢一個月中特定的一天?

編輯:編程綜合問答
如何查詢一個月中特定的一天?

研究了很久NSDateNSDateFormatterNSCalendar,不知道怎麼實現找出一月個中指定一天的功能。比如查詢十二月第二個星期一的日期是多少,不知道怎麼實現呢?

謝謝指教。

最佳回答:


謝謝回答者的答案,我根據得到的回答,實現了。最後這樣的

    -(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];
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved