最近有一個功能,需要計算同一天內(nèi)兩個時間之間的差值,開始打算將NSDate先轉(zhuǎn)換成NSString,然后轉(zhuǎn)后成int類型數(shù)據(jù)進(jìn)行換算對比。
但是這種方法太過繁瑣,時間之間的對比要逐一對比小時分鐘,然后還要將結(jié)果進(jìn)行轉(zhuǎn)換,實在是麻煩。這里我使用了NSCalendar類。
下面來看一下具體的實現(xiàn):
首先先拿到當(dāng)前時間,并轉(zhuǎn)換成字符串:
//獲取當(dāng)前時間
NSDate *date = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"HH:mm"];
NSString *dateStr = [formatter stringFromDate:date];
同樣也將要比較的時間(我們這里將其稱為開始時間)轉(zhuǎn)換成相同格式的字符串:
//開始時間
NSString *beginTime = dict[@"BeginTime"];
下面進(jìn)入正題,比較兩個時間字符串:
//計算當(dāng)前時間和開始時間的差值
NSCalendar *calendar = [NSCalendar currentCalendar];
NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth
| NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
//對比時間差
NSDateComponents *component = [calendar components:unit fromDate:beginDate toDate:nowDate options:0];
NSLog(@"年差額 = %ld, 月差額 = %ld, 日差額 = %ld, 小時差額 = %ld, 分鐘差額 = %ld, 秒差額 = %ld",(long)component.year,component.month,component.day,component.hour,component.minute,component.second);
這樣我們就分別得到了年、月、日、時、分、秒的差額,如果你想要得到一個時間相差總額,比如說一天內(nèi)兩個時間點之間的總差額,你只需要進(jìn)行簡單的計算:component.hour *60 + component.minute即可得到兩個時間總共相差的分鐘數(shù)。