同步请求当前网络北京时间

基于 http://www.jianshu.com/p/ffc758b8eb0e 的修改。

由于使用[NSDate date]来获取当前时间是不准确的,因为用户可能会将设备的时间修改了,[NSDate date]的值是基于当前设备设定的时间。
所以只能通过网络的来获取当前时间。

  • ATS需添加域名白名单m.baidu.com
  • 使用信号量同步NSURLSession 网络请求
  • GMT时区转换成当前中国北京时区
/*!
 获取网络的当前北京时间(不受因用户改设备时间影响,准确),同步请求
 ATS需添加域名白名单m.baidu.com
 <key>NSExceptionDomains</key>
 <dict>
 <key>m.baidu.com</key>
 <dict>
 <key>NSExceptionAllowsInsecureHTTPLoads</key>
 <true/>
 </dict>
 </dict>
 */
+ (instancetype)getCurrentPlus8InterneDate{
    NSString *urlString = @"http://m.baidu.com";
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString: urlString]];
    [request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
    [request setTimeoutInterval: 2];
    [request setHTTPShouldHandleCookies:FALSE];
    [request setHTTPMethod:@"GET"];
    __block NSHTTPURLResponse *mResponse;
    
    dispatch_semaphore_t semaphare = dispatch_semaphore_create(0); //使用信号量来同步请求
    
    [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        mResponse = (NSHTTPURLResponse *)response;
        dispatch_semaphore_signal(semaphare);
    }] resume];
    dispatch_semaphore_wait(semaphare, DISPATCH_TIME_FOREVER);
    
    NSString *date = [[mResponse allHeaderFields] objectForKey:@"Date"];
    NSDateFormatter *dMatter = [[NSDateFormatter alloc] init];
    dMatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    [dMatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss Z"]; //Tue, 17 Jan 2017 07:22:52 GMT
    NSDate * netDate = [dMatter dateFromString:date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: netDate];
    NSDate *localeDate = [netDate  dateByAddingTimeInterval: interval];
    return localeDate;
}

也可以通过自己服务器,和获取内核kernel的时间算出时间偏移,来算出准确的时间段

//ObjC
NSTimeInterval systemUptime =[[NSProcessInfo processInfo] systemUptime];
//swift
var systemUptime = ProcessInfo().systemUptime;

参考 http://www.jianshu.com/p/82475b5a7e19

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 在iOS开发中,经常会遇到各种各样的时间问题,8小时时差,时间戳,求时间间隔,农历等等。解决办法网上比比皆是,但大...
    真巧了_嘿阅读 7,841评论 0 7
  • iOS开发中,经常会遇到各种各样的时间问题,8小时时差,时间戳,求时间间隔,农历等等。解决办法网上比比皆是,但大多...
    小李龍彪阅读 11,649评论 1 6
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 177,223评论 25 709
  • 那一年冬天梅花在枝头绽放, 你我相爱共同许下爱情诺言。 不论今生能够携手走过多远, 十年以后都在老地方再相见。 分...
    得我者幸阅读 1,607评论 0 2

友情链接更多精彩内容