本文共 2944 字,大约阅读时间需要 9 分钟。
+(NSString*)GetDetailTime{ //获得系统时间 NSDate * senddate=[NSDate date]; NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init]; //[dateformatter setLocale:[NSLocale localeWithLocaleIdentifier:@""]]; [dateformatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; NSString * morelocationString=[dateformatter stringFromDate:senddate]; // NSArray*array=[morelocationString componentsSeparatedByString:@"-"]; return morelocationString;}
//计算当前时间往后推days天-(NSDate *)dateAfterDays:(int)days{ NSCalendar *calendar = [NSCalendar currentCalendar]; unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit; NSDateComponents *components = [calendar components:unitFlags fromDate:[NSDate date]]; [components setDay:([components day]+days)]; return [calendar dateFromComponents:components];}
//获取网络服务器时间+(void)getNetTimeWithCompleteHandle:(void(^)(BOOL isSuccess,NSDate* date))complete{ AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; NSString * urlstr = @"https://www.baidu.com"; NSURL *url = [NSURL URLWithString:urlstr]; NSMutableURLRequest *muRequest = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:2.0f]; muRequest.HTTPMethod = @"GET"; NSURLSessionDataTask *task = [manager dataTaskWithRequest:muRequest completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { //} NSHTTPURLResponse *httpResponse=(NSHTTPURLResponse *)response; //if ([response respondsToSelector:@selector(allHeaderFields)]) { NSDictionary *dict=[httpResponse allHeaderFields]; NSString *time=[dict objectForKey:@"Date"]; NSString *timeStr=[time substringWithRange:NSMakeRange(5, 20)];//截取字符串 NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"GMT"]; NSLocale *local=[[NSLocale alloc]initWithLocaleIdentifier:@"en_US_POSIX"]; [formatter setLocale:local];//需要配置区域,不然会造成模拟器正常,真机日期为null的情况 [formatter setTimeZone:timeZone]; [formatter setDateFormat:@"dd MMM yyyy HH:mm:ss"];//设置源时间字符串的格式 NSDate* date = [formatter dateFromString:timeStr];//将源时间字符串转化为NSDate long timesecond = date.timeIntervalSince1970; if (error==nil) { complete(YES,date); }else{ complete(NO,date); } }]; [task resume];}
//计算两个时间差是几天NSDateFormatter *formater= [[ NSDateFormatter alloc]init]; [formater setDateFormat:@"yy/MM/dd"]; NSDate * expireD = [formater dateFromString:expireDate]; NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian]; NSDateComponents *comps = [gregorian components:NSCalendarUnitEra fromDate:expireD1 toDate:expireD options:0]; NSInteger days = [comps day]; NSLog(@"%ld天",(long)days);
转载地址:http://vlnvb.baihongyu.com/