为了避免任何日期和时间问题,我计划从我自己的服务器
获取日期。
所以我在 PHP
文件中编写了这段代码,并将该文件上传到我的服务器。
Date.php
<?php
date_default_timezone_set('Asia/Kolkata');
$date = date('d/m/Y', time());
echo $date;
?>
现在要访问它,我正在使用这段代码:
NSURL *url = [NSURL URLWithString:@"http://www.myserver.com/date.php"];
NSError* error;
NSString *content = [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:&error];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"dd/MM/yyyy"];
NSDate *serverDate = [dateFormat dateFromString:content];
NSDate *DeviceDate = [NSDate date];
Not the main Root Cause
我的系统日期设置为当前日期和时间。现在,当我调试我得到的代码时:
serverDate = 2015-12-27 18:30:00 +0000
和
deviceDate = 2015-12-28 10:35:16 +0000
我无法理解为什么这两个日期之间相差一天。我缺少什么?
最佳答案
在此函数中传递两个日期。它是 UTC 返回日期。
NSTimeZone *currentTimeZone = [NSTimeZone localTimeZone];
NSTimeZone *utcTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
NSInteger currentGMTOffset = [currentTimeZone secondsFromGMTForDate:YourDate];
NSInteger gmtOffset = [utcTimeZone secondsFromGMTForDate:YourDate];
NSTimeInterval gmtInterval = currentGMTOffset - gmtOffset;
NSDate *destinationDate = [[NSDate alloc] initWithTimeInterval:gmtInterval sinceDate:YourDate] ;
关于php - 在 Xcode 6.4 中从服务器获取当前日期和时间时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34491985/