iOS 获取两个时间刻度之间的时间数组,或者指定时间间隔

背景

有个业务需求就是需要在15:05:00 ~ 15:30:00 时间间隔为15秒, 获取其中的所有时间点的时间数组, 时间格式为 150500, 153000, 本来想着统一转换为秒来计算, 但是总感觉这样就需要一直装换时间格式, 挺繁琐就写了以下的通用方式来获取时间数组

废话不多说直接上代码

/**
 * 根据起始时间和结束时间,以及时间间隔,来返回时间数组(时间必须是113000, 这种格式的)
 * @param begin 起始时间
 * @param end 结束时间
 * @param interval 时间间隔
 */
+ (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 并且时间间隔需要大于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];
        
        /**< 先加入初始时间 */
        [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;
}

/**< 确保两位数 */
+ (NSString *)getFormatStringWithTime:(int)time
{
    NSString *resultString = @"";
    if ([NSString stringWithFormat:@"%@", @(time)].length == 1) {
        /**< 如果秒位上只有一位数, 则补0  例如 秒为1,  则补为 01 保持时间长度不变*/
        resultString = [NSString stringWithFormat:@"0%@", @(time)];
    }else{
        resultString = [NSString stringWithFormat:@"%@",@(time)];
    }
    return resultString;
}

这样就可以方便的获取时间数组,有好的通用方法,欢迎交流

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。