iOS 獲取兩個(gè)時(shí)間刻度之間的時(shí)間數(shù)組,或者指定時(shí)間間隔

背景

有個(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)];

    /**< 確保長度為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í)間長度不變*/
        resultString = [NSString stringWithFormat:@"0%@", @(time)];
    }else{
        resultString = [NSString stringWithFormat:@"%@",@(time)];
    }
    return resultString;
}

這樣就可以方便的獲取時(shí)間數(shù)組,有好的通用方法,歡迎交流

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容