iOS获取时间差 获取时间 是否是24小时制

直接上代码

// 本地时间与其他时间对比,判断是否超过固定时间
+ (BOOL)overtime:(NSString *)serverTime maxSecond:(CGFloat)maxSec
{
    if (serverTime.length == 0 || maxSec < 0) {
        return NO;
    }
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
//    fmt.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
//    fmt.locale =[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
    if ([self is12Or24Time]) {
        fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    }else{
        fmt.dateFormat = @"yyyy-MM-dd hh:mm:ss";
    }
    NSDate *serverDate = [fmt dateFromString:serverTime];
//    NSInteger min = [[NSDate date] minutesAfterDate:serverDate];
    if (serverDate == nil) {
        return NO;
    }
    NSTimeInterval timeDiff = [[NSDate date] timeIntervalSinceDate:serverDate];
    NSLog(@"------%.f-------",timeDiff);
    if (fabs(timeDiff) > maxSec) {
        return YES;
    }
    return NO;
}

//当前时间 str类型
+ (NSString *)getCurrentTimeString
{
    NSString *sss = @"yyyy-MM-dd hh:mm:ss";
    if ([self is12Or24Time]) {
        sss = @"yyyy-MM-dd HH:mm:ss";
    }
    NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
    [formatter setDateFormat:sss];
    NSString *dateTime=[formatter stringFromDate:[NSDate date]];
    return dateTime;
}
+ (BOOL)is12Or24Time
{
    //获取系统是24小时制或者12小时制
    NSString*formatStringForHours = [NSDateFormatter dateFormatFromTemplate:@"j" options:0 locale:[NSLocale currentLocale]];
    NSRange containsA = [formatStringForHours rangeOfString:@"a"];
    BOOL hasAMPM = containsA.location != NSNotFound;
    //hasAMPM==TURE为12小时制,否则为24小时制
    return hasAMPM;
}

你可能感兴趣的:(iOS获取时间差 获取时间 是否是24小时制)