對(duì)時(shí)間處理,在開(kāi)發(fā)時(shí),時(shí)常碰到。一般有獲取具體的年月日和星期,兩個(gè)不同時(shí)間的差,某一天的前一天或后一天等;在這里我只介紹獲取具體的年月日和星期,及某一天的前一天或后一天的方法;
對(duì)時(shí)間的處理一般都會(huì)用到NSDate類和NSCalendar類兩個(gè)類;
獲取當(dāng)前的時(shí)間是:NSDate *nowDate = [NSDate date];獲取具體的年月日就是對(duì)nowDate的處理;一般要用到NSCalendar類,首先是對(duì)NSCalendar的聲明,再就是屬性的設(shè)置, 其中屬性[calendar components:(...)];很重要;設(shè)置了屬性就可以根據(jù)方法獲取年月日,如int nowYear = [comps year];
獲取星期要先獲取int nowWeek = [comps weekday];再對(duì)nowweek的值進(jìn)行判斷,值是從1到7,分別對(duì)應(yīng)的星期是從星期天到星期六。
代碼如下:
NSDate *nowDate = [NSDate date]; //這是當(dāng)前的時(shí)間,其實(shí)這里可以是任意時(shí)間
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *comps;
comps = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:nowDate];
int nowYear = [comps year];
int nowMonth = [comps month];
int nowDay = [comps day];
int nowWeek = [comps weekday];
NSString *weekStr = [[NSString alloc] init];
switch (nowWeek) {
case 1:
weekStr = @"星期天";
break;
case 2:
weekStr = @"星期一";
break;
case 3:
weekStr = @"星期二";
break;
case 4:
weekStr = @"星期三";
break;
case 5:
weekStr = @"星期四";
break;
case 6:
weekStr = @"星期五";
break;
case 7:
weekStr = @"星期六";
break;
default:
break;
}
NSLog(@"年:%d;月:%d;日:%d;%@",nowYear,nowMonth,nowDay,weekStr);
某一天的前一天或后一天的方法:
這里要用到的是NSCalendar,首先也是設(shè)置屬性,和上面一樣;用到最主要的方法是[comps setHour:+24];+24表示獲取下一天,-24表示獲取前一天;還有[comps setMinute:0]和[comps setSecond:0]都要;
最后將calendar轉(zhuǎn)換成NSdate;方法如下:
NSDate *nowDate = [calendar dateByAddingComponents:comps toDate:showDate options: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:showDate options:0]; //showDate表示某天的date,nowDate表示showDate的前一天或下一天的date
更多信息請(qǐng)查看IT技術(shù)專欄