背景
有個(gè)業(yè)務(wù)需求就是需要在15:05:00 ~ 15:30:00 時(shí)間間隔為15秒, 獲取其中的所有時(shí)間點(diǎn)的時(shí)間數(shù)組, 時(shí)間格式為 150500, 153000, 本來想著統(tǒng)一轉(zhuǎn)換為秒來計(jì)算, 但是總感覺這樣就需要一直裝換時(shí)間格式, 挺繁瑣就寫了以下的通用方式來獲取時(shí)間數(shù)組
廢話不多說直接上代碼
/**
* 根據(jù)起始時(shí)間和結(jié)束時(shí)間,以及時(shí)間間隔,來返回時(shí)間數(shù)組(時(shí)間必須是113000, 這種格式的)
* @param begin 起始時(shí)間
* @param end 結(jié)束時(shí)間
* @param interval 時(shí)間間隔
*/
+ (NSArray *)getFormatterTimeArrayWithBegin:(int)begin
end:(int)end
interval:(int)interval
{
NSMutableArray *tempTimeArray = [NSMutableArray array];
int beginTime = begin;
int endTime = end;
int timeInterval = interval;
NSString *beginTimeString = [NSString stringWithFormat:@"%@",@(beginTime)];
NSString *endTimeString = [NSString stringWithFormat:@"%@",@(endTime)];
/**< 確保長(zhǎng)度為6 并且時(shí)間間隔需要大于0 */
if (beginTimeString.length == 6 && endTimeString.length == 6 && interval > 0) {
int h = [[beginTimeString substringWithRange:NSMakeRange(0, 2)] intValue];
int m = [[beginTimeString substringWithRange:NSMakeRange(2, 2)] intValue];
int s = [[beginTimeString substringWithRange:NSMakeRange(4, 2)] intValue];
/**< 先加入初始時(shí)間 */
[tempTimeArray addObject:beginTimeString];
NSString *resultTime = @"";
while (beginTime < endTime) {
s += timeInterval;
if (s == 60) {
s -= 60;
m += 1;
if (m == 60) {
m -= 60;
h += 1;
if (h == 24) {
h -= 24;
}
}
}
resultTime = [NSString stringWithFormat:@"%@%@%@",[[self class] getFormatStringWithTime:h], [[self class] getFormatStringWithTime:m], [[self class] getFormatStringWithTime:s]];
beginTime = [resultTime intValue];
[tempTimeArray addObject:resultTime];
}
}
return tempTimeArray;
}
/**< 確保兩位數(shù) */
+ (NSString *)getFormatStringWithTime:(int)time
{
NSString *resultString = @"";
if ([NSString stringWithFormat:@"%@", @(time)].length == 1) {
/**< 如果秒位上只有一位數(shù), 則補(bǔ)0 例如 秒為1, 則補(bǔ)為 01 保持時(shí)間長(zhǎng)度不變*/
resultString = [NSString stringWithFormat:@"0%@", @(time)];
}else{
resultString = [NSString stringWithFormat:@"%@",@(time)];
}
return resultString;
}
這樣就可以方便的獲取時(shí)間數(shù)組,有好的通用方法,歡迎交流