我目前正在投标申请,投标APP的工作主要基于我用来计算时间的时间
NSLog(@"date %d",(int)[[NSDate date] timeIntervalSince1970]);
output:1409031539
我占用了服务器时间并比较了设备时间和计算时间,但是在更改时区时,这个非工作时间因使用此代码而变化。
NSLocale* currentLocale = [NSLocale currentLocale];
NSLog(@"date: %d",(int)[[NSDate date] descriptionWithLocale:currentLocale]);
输出:196208512
但这并没有帮助我计算运行代码的时间,我看到了不同的输出。
答案 0 :(得分:0)
这一行:
NSLog(@"date: %d",(int)[[NSDate date] descriptionWithLocale:currentLocale]);
如此错误让我感到疼痛。来自descriptionWithLocale
的返回数据为NSString *
,而不是NSTimeInterval
,将其打印为int
只是将指针转换为int
,这是一个NSLocale* currentLocale = [NSLocale currentLocale];
NSTimeInterval nsti = [[NSDate date] timeIntervalSince1970];
NSLog(@"date (as seconds from 1970): %ld", (long)nsti);
NSLog(@"date (as locale-relative string): %@", [[NSDate dateWithTimeIntervalSince1970:nsti] descriptionWithLocale:currentLocale]);
// This is Mon 25 Aug 2014, 20:17:51 BST (UTC +0100) obtained by date +%s, subtracting 60,000
NSTimeInterval time_from_server = 1408994271;
NSLog(@"date (from server as string): %@", [[NSDate dateWithTimeIntervalSince1970:time_from_server] descriptionWithLocale:currentLocale]);
在最好的时候坏主意。
我假设您的服务器返回的时间戳也是1970年后的#seconds,所以我只是在这段代码中硬编码了一个例子:
NSDate
请注意,NSTimeInterval
或NSTimeZone
都没有任何时区概念,因此不具有偏离GMT的概念。你需要的是GMT
。请记住,NSTimeZone *localZone = [NSTimeZone localTimeZone];
NSDate *date111 = [NSDate date];
NSInteger delta = [localZone secondsFromGMTForDate:date111];
NSLog(@"date= %ld", (long)delta);
的偏移量取决于当前日期/时间(例如夏令时,冬令时),您必须使用如下代码:
NSTimeZone *phoenix = [NSTimeZone timeZoneWithName:@"America/Phoenix"];
NSTimeZone *dublin = [NSTimeZone timeZoneWithName:@"Europe/Dublin"];
NSTimeZone *tokyo = [NSTimeZone timeZoneWithName:@"Asia/Tokyo"];
NSDate *date111 = [NSDate date];
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
[fmt setDateStyle:NSDateFormatterFullStyle];
[fmt setTimeStyle:NSDateFormatterFullStyle];
[fmt setLocale:[NSLocale currentLocale]];
[fmt setTimeZone:phoenix];
NSLog(@"phoenix %@", [fmt stringFromDate:date111]);
[fmt setTimeZone:dublin];
NSLog(@"dublin %@", [fmt stringFromDate:date111]);
[fmt setTimeZone:tokyo];
NSLog(@"tokyo %@", [fmt stringFromDate:date111]);
获取时区,获取日期,从GMT获取该日期的偏移量,记录下来。
将时间显示为特定时区的当地时间:
phoenix Tuesday, August 26, 2014 at 9:33:12 AM Mountain Standard Time
dublin Tuesday, August 26, 2014 at 5:33:12 PM Irish Summer Time
tokyo Wednesday, August 27, 2014 at 1:33:12 AM Japan Standard Time
给我(截至目前):
{{1}}
这里的基本概念是:
因此,考虑到这一点,当您获得设备时间时,它只是一个NSDate或NSTimeInterval,这意味着不将时区编码为它