【作者前言】:13年入圈,分享些本人工作中遇到的點(diǎn)點(diǎn)滴滴那些事兒,17年剛開(kāi)始寫(xiě)博客,高手勿噴!以分享交流為主,歡迎各路豪杰點(diǎn)評(píng)改進(jìn)!
1.應(yīng)用場(chǎng)景:
實(shí)際工作中,經(jīng)常會(huì)用到時(shí)間之間的比較
2.實(shí)現(xiàn)目標(biāo):
簡(jiǎn)述常用的各種NSDate時(shí)間之間比較的方法
3.代碼說(shuō)明:
1.直觀比較,沒(méi)有計(jì)算時(shí)間差值;
/** 與otherDate比較,時(shí)間相同返回YES*/
- (BOOL)isEqualToDate:(NSDate *)otherDate;
/**與anotherDate比較,返回較早的那個(gè)日期*/
- (NSDate *)earlierDate:(NSDate *)anotherDate;
/**與anotherDate比較,返回較晚的那個(gè)日期*/
- (NSDate *)laterDate:(NSDate *)anotherDate;
- (NSComparisonResult)compare:(NSDate *)other;
該方法用于排序時(shí)調(diào)用:
. 當(dāng)實(shí)例保存的日期值與anotherDate相同時(shí)返回NSOrderedSame
. 當(dāng)實(shí)例保存的日期值晚于anotherDate時(shí)返回NSOrderedDescending
. 當(dāng)實(shí)例保存的日期值早于anotherDate時(shí)返回NSOrderedAscending
2.計(jì)算時(shí)間差,根據(jù)已有時(shí)間差算出另一個(gè)時(shí)間點(diǎn)
/** 計(jì)算明天這個(gè)時(shí)間點(diǎn)*/
NStimeInterval a_daySecond = 60*60*24;
NSDate *tommorrow = [NSDate dateWithTimeIntervalSinceNow:a_daySecond];
/** 根據(jù)已知時(shí)間,求相差 timeInterval s后的時(shí)間*/
NStimeInterval timeInterval = 60*60;
NSDate *date = [NSDate date];
NSDate *needDate = [date addTimeInterval:timeInterVal];
/** 比較明天與現(xiàn)在時(shí)間相差多少秒*/
NSDate *date = [NSDate date];
NSTimeInterval secondsInterval = [date timeIntervalSinceDate:tomorrow];