即便你滿腹經(jīng)綸镣典,如果你自命清高從不寫(xiě)作、把知識(shí)分享給別人也只能是默默無(wú)聞壁涎。即便你武功蓋世,如果不鋤強(qiáng)扶弱盹舞、匡扶正義,也難成一代大俠。
問(wèn)題緣由:工程需要選擇一個(gè)開(kāi)始時(shí)間和一個(gè)結(jié)束時(shí)間,結(jié)束時(shí)間必須要大于開(kāi)始時(shí)間.這就需要到比較時(shí)間的大小了,下面提供兩種方法,第一種方法是NSDate自帶的方法,第二種是對(duì)其的封裝,根據(jù)情況酌情處理.
方法一、NSDate自帶的系統(tǒng)方法
日期之間比較可用以下方法
- (BOOL)isEqualToDate:(NSDate *)otherDate;
與otherDate比較花竞,相同返回YES
- (NSDate *)earlierDate:(NSDate *)anotherDate;
與anotherDate比較劲件,返回較早的那個(gè)日期
- (NSDate *)laterDate:(NSDate *)anotherDate;
與anotherDate比較掸哑,返回較晚的那個(gè)日期
- (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
方法二、對(duì)其中的 - (NSComparisonResult)compare:(NSDate *)other;進(jìn)行封裝
+(int)compareOneDay:(NSDate *)oneDay withAnotherDay:(NSDate *)anotherDay
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSString *oneDayStr = [dateFormatter stringFromDate:oneDay];
NSString *anotherDayStr = [dateFormatter stringFromDate:anotherDay];
NSDate *dateA = [dateFormatter dateFromString:oneDayStr];
NSDate *dateB = [dateFormatter dateFromString:anotherDayStr];
NSComparisonResult result = [dateA compare:dateB];
if (result == NSOrderedDescending) {
//NSLog(@"oneDay比 anotherDay時(shí)間晚");
return 1;
}
else if (result == NSOrderedAscending){
//NSLog(@"oneDay比 anotherDay時(shí)間早");
return -1;
}
//NSLog(@"兩者時(shí)間是同一個(gè)時(shí)間");
return 0;
}
方法二使用注意事項(xiàng):首先,方法二的方法是一個(gè)類方法,我一般會(huì)把它寫(xiě)在NSDate的延展當(dāng)中,或者把它寫(xiě)成一個(gè)對(duì)象方法,在對(duì)應(yīng)的類中,使用self調(diào)用.其實(shí),第二個(gè)方法是對(duì)年月日這三級(jí)進(jìn)行比較,時(shí)分秒并沒(méi)有添加進(jìn)來(lái)如果需要的需要修改dateFormatter的@"dd-MM-yyyy"格式改成你想要比較的級(jí)數(shù).
結(jié)束語(yǔ):在程序開(kāi)發(fā)的道路上就是不斷學(xué)習(xí)的過(guò)程,不是嗎?與君共勉!