項(xiàng)目中肯定會(huì)有很多獲取時(shí)間進(jìn)行計(jì)算的地方
獲取當(dāng)前時(shí)間
NSDate *date = [NSDate date];
NSLog(@"%@", date);
打印出來(lái)會(huì)發(fā)現(xiàn)會(huì)比當(dāng)前時(shí)間少幾個(gè)小時(shí)因?yàn)檫@里的時(shí)間是世界標(biāo)準(zhǔn)時(shí)間
所以為了獲取我們的時(shí)間得這樣
//通過(guò)系統(tǒng)時(shí)間獲取時(shí)間zone
NSTimeZone *zone = [NSTimeZone systemTimeZone];
//通過(guò)zone獲取跟標(biāo)準(zhǔn)時(shí)間的時(shí)間差
NSInteger interval = [zone secondsFromGMTForDate: date];
//最后通過(guò)時(shí)間差獲取當(dāng)前時(shí)間
NSDate *localDate = [date? dateByAddingTimeInterval: interval];
獲取了當(dāng)前時(shí)間,我們一般不全會(huì)用,需要通過(guò)已知時(shí)間分別獲取年月日時(shí)分秒等來(lái)進(jìn)行需要的操作需要NSDateComponents這個(gè)類,類似一個(gè)裝時(shí)間的容器
//獲取時(shí)間日歷
NSCalendar *calendar = [NSCalendar currentCalendar];
//在這里把需要裝入容器的時(shí)間枚舉類型都連上
NSUInteger unitFlags = NSCalendarUnitYear|NSCalendarUnitMonth |NSCalendarUnitDay|NSCalendarUnitWeekday;
//基本的幾個(gè)如下,
NSCalendarUnitYear? ? ? ? ? ? //年
NSCalendarUnitMonth? ? ? //月
NSCalendarUnitDay? ? ? ? ? ? ? //日
NSCalendarUnitHour? ? ? ? //時(shí)
NSCalendarUnitMinute? ? ? ? //分
NSCalendarUnitSecond? ? ? ? //秒
NSCalendarUnitWeekday? ? ? ? ? //星期
NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:date];
然后通過(guò)獲取dateComponent的屬性獲取相應(yīng)的值
例如 我要獲取年份
NSInteger week=dateComponent.year;
這樣可以在項(xiàng)目中對(duì)時(shí)間進(jìn)行各種操作了