iOS开发中使用ios-ntp获取正确的时间

0.ntp.png

我们有时需要获取一个时间,但如果只是从本地直接获取有可能因为手机系统时间是错误(用户修改了系统时间)的而导致我们获取到的是一个错误的时间。此时就需要我们从网络获取一个正确的时间。

iOS开发中有人写了NetworkClock这样一个类来获取时间。
github地址:https://github.com/jbenet/ios-ntp

使用:

  NSDate * date = [[NetworkClock sharedNetworkClock] networkTime];
NSUInteger timestamp = [NSString stringWithFormat:@"%f", [date timeIntervalSince1970] * 1000].integerValue;
   NSLog(@"timestamp:%lu", timestamp);
NSString * dateStr = [date ls_getDateStringWithDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSLog(@"dateStr:%@", dateStr);

打印:

  6.NetworkClock使用[7060:482670] timestamp:1594631953867
  6.NetworkClock使用[7060:482670] dateStr:2020-07-13 17:19:13

通过[[NetworkClock sharedNetworkClock] networkTime]获取到的是一个NSDate类型数据,我将其转成了时间字符串进行打印。

后期发现这样方式是有问题的,大家可以看看demo中的方法:
demo地址:https://github.com/yangguanghei/networkTime

本篇文章到这里就结束了,愿大家加班不多工资多,男同胞都有女朋友,女同胞都有男朋友。

你可能感兴趣的:(iOS开发中使用ios-ntp获取正确的时间)