對時間的處理通常都會用到NSDate類和NSCalendar類兩個類。spa
獲取當前的時間是:NSDate *nowDate = [NSDate date];獲取具體的年月日就是對nowDate的處理;通常要用到NSCalendar類,首先是對NSCalendar的聲明,再就是屬性的設置, 其中屬性[calendar components:(...)];很重要;設置了屬性就能夠根據方法獲取年月日,如int nowYear = [comps year];component
獲取星期要先獲取int nowWeek = [comps weekday];再對nowweek的值進行判斷,值是從1到7,分別對應的星期是從星期天到星期六。orm
代碼以下:it
NSDate *date = [NSDate date]; io
NSCalendar *calendar = [NSCalendar currentCalendar];object
NSDateComponents *comps = [calendar components:(NSCalendarUnitYear |date
NSCalendarUnitMonth |方法
NSCalendarUnitDay |im
NSCalendarUnitWeekday |margin
NSCalendarUnitHour |
NSCalendarUnitMinute |
NSCalendarUnitSecond) fromDate:date];
NSInteger nowYear = [comps year];
NSInteger nowMonth = [comps month];
NSInteger nowDay = [comps day];
NSInteger nowWeek = [comps weekday];
NSInteger nowHour = [comps hour];
NSInteger nowMinute = [comps minute];
NSArray * arrayWeek=[NSArray arrayWithObjects:@"週日",@"週一",@"週二",@"週三",@"週四",@"週五",@"週六",nil];
NSLog(@"%ld年%ld月%ld日 %@ %ld:%ld",nowYear,nowMonth,nowDay,[arrayWeekobjectAtIndex:nowWeek-1],nowHour,nowMinute);
某一天的前一天或後一天的方法:
這裏要用到的是NSCalendar,首先也是設置屬性,和上面同樣;用到最主要的方法是[comps setHour:+24];+24表示獲取下一天,-24表示獲取前一天;還有[comps setMinute:0]和[comps setSecond:0]都要;
最後將calendar轉換成NSdate;方法以下:
NSDate *nowDate = [calendar dateByAddingComponents:comps toDate:showDateoptions:0];//showDate表示某天的date,nowDate表示showDate的前一天或下一天的date
代碼以下:
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *comps;
comps = [calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit |NSSecondCalendarUnit) fromDate:[[NSDate alloc] init]];
[comps setHour:+24]; //+24表示獲取下一天的date,-24表示獲取前一天的date;
[comps setMinute:0];
[comps setSecond:0];
NSDate *nowDate = [calendar dateByAddingComponents:comps toDate:showDateoptions:0];//showDate表示某天的date,nowDate表示showDate的前一天或下一天的date
【負責編輯:Alan_JL】