iOS 规定的时间段内调用事件

用法:

//@"yyyy-MM-dd HH:mm"

       if ([NSDate judgeTimeByStartAndEnd:@"12:00" EndTime:@"18:00" DateFormat:@"HH:mm"]) {

           NSLog(@"在当前时间段里面");

       }else{

           NSLog(@"不在当前时间段里面");

       }

方法:

+(BOOL)judgeTimeByStartAndEnd:(NSString*)startStrEndTime:(NSString*)endStrDateFormat:(NSString*)format

{

    //获取当前时间 @"yyyy-MM-dd HH:mm"

    NSDate*today = [NSDategetInternetDate];

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];

    // 时间格式,建议大写    HH 使用 24 小时制;hh 12小时制

    [dateFormatsetDateFormat:format];

     NSString* todayStr=[dateFormatstringFromDate:today];//将日期转换成字符串

    today=[ dateFormatdateFromString:todayStr];//转换成NSDate类型。日期置为方法默认日期

    //start end 格式 "2016-05-18 9:00:00"

    NSDate*start = [[dateFormatdateFromString:startStr]dateByAddingTimeInterval:60*60*8];

    NSDate*expire = [[dateFormatdateFromString:endStr]dateByAddingTimeInterval:60*60*8];

//    NSDate *netDate = [[dMatter dateFromString:date] dateByAddingTimeInterval:60*60*8];//时间差8小时

    if ([today compare:start] == NSOrderedDescending && [today compare:expire] == NSOrderedAscending) {

        returnYES;

    }

    return NO;

}

+ (NSDate *)getInternetDate

{

    NSString *urlString = @"http://m.baidu.com";

    urlString = [urlStringstringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];

    // 实例化NSMutableURLRequest,并进行参数配置

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

    [requestsetURL:[NSURLURLWithString: urlString]];

    [requestsetCachePolicy:NSURLRequestReloadIgnoringCacheData];

    [requestsetTimeoutInterval: 2];

    [requestsetHTTPShouldHandleCookies:FALSE];

    [requestsetHTTPMethod:@"GET"];

    NSError*error =nil;

    NSHTTPURLResponse *response;

    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

    // 处理返回的数据

    if(error) {

        return[NSDatedate];

    }

    NSString*date = [[responseallHeaderFields]objectForKey:@"Date"];

    date = [datesubstringFromIndex:5];//index到这个字符串的结尾

    date = [datesubstringToIndex:[datelength]-4];//从索引0到给定的索引index

    NSDateFormatter *dMatter = [[NSDateFormatter alloc] init];

    dMatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];

    [dMattersetDateFormat:@"dd MMM yyyy HH:mm:ss"];

    NSDate*netDate = [[dMatterdateFromString:date]dateByAddingTimeInterval:60*60*8];//时间差8小时

    NSTimeZone *zone = [NSTimeZone systemTimeZone];

    NSIntegerinterval = [zonesecondsFromGMTForDate: netDate];

    netDate = [netDatedateByAddingTimeInterval: interval];

    returnnetDate;

}


希望对你有用!!!

你可能感兴趣的:(iOS 规定的时间段内调用事件)