项目中有这样一处功能:前台判断是否到了服务器给返回的那个时间点,不到不能进行相应的处理。开始是获取的系统时间,但发现,手机里是可以更改系统时间的,这样就会出现功能漏洞,当然,后台也判断是更加稳妥的,只不过,前台判断了,可以减少访问服务器的压力嘛。
于是这里做下笔记:
获取系统时间:NSDate *curDate = [NSDate date];
注意NSDate 返回值格式:2020-05-14 09:03:03 +0000 (实际时间是17:03)
要注意8小时时间差问题
获取网络时间
+ (NSDate *)getInternetDate
{
NSString *urlString = @"http://m.baidu.com";
urlString = [urlStringstringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[requestsetURL:[NSURLURLWithString: urlString]];
[requestsetCachePolicy:NSURLRequestReloadIgnoringCacheData];
[requestsetTimeoutInterval:2];
[requestsetHTTPShouldHandleCookies:FALSE];
[requestsetHTTPMethod:@"GET"];
NSHTTPURLResponse *response;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
NSString*date = [[responseallHeaderFields]objectForKey:@"Date"];
date = [datesubstringFromIndex:5];
date = [datesubstringToIndex:[datelength]-4];
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];
// NSDate *netDate = [dMatter dateFromString:date];
NSTimeZone *zone = [NSTimeZone systemTimeZone];
NSIntegerinterval = [zonesecondsFromGMTForDate: netDate];
NSDate*localeDate = [netDate dateByAddingTimeInterval: interval];
returnlocaleDate;
}
调用:NSDate*current = [ToolPublicgetInternetDate];
网友评论