来自(NSDate) - > NSTimeInterval到不相关的类型'NSTimeInterval总是失败

时间:2015-09-15 05:45:58

标签: ios swift

我正在尝试从iPad到我的网站的时间差异,这些都是本地的。一切正常,直到我到达下面的行,这应该占用iPad的时间并从中减去serverTime。

self.serverTimeOffSet = NSDate.timeIntervalSinceDate(serverTime) as NSTimeInterval

我收到警告“从(NSDate) - > NSTimeInterval转换为无关类型'NSTimeInterval始终失败”,并且永远不会设置self.serverTimeOffset。

var serverTimeOffSet: NSTimeInterval = 0.0

func setServerOffset(){
    var currentTime = NSDate.timeIntervalSinceReferenceDate()
    var url = NSURL(string: "http://someurl.com/time")
    var request = NSMutableURLRequest(URL:url!)
    var response: NSURLResponse?
    var error: NSError?
    request.HTTPMethod = "get"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response:NSURLResponse!, data:NSData!, error:NSError!) -> Void in
        if (error == nil) {
            var dateString = NSString(data: data, encoding: NSUTF8StringEncoding) as! String
            let dateFormatter = NSDateFormatter()
            dateFormatter.dateFormat = "YYYY-MM-dd'T'HH:mm:ss"
            dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
            if let serverTime = dateFormatter.dateFromString(dateString){
                self.serverTimeOffSet = NSDate.timeIntervalSinceDate(serverTime) as NSTimeInterval
            }
        }
    })
}

由于

编辑 - 从网站返回日期:

2015-09-15T00:01:44.8530546-06:00

2 个答案:

答案 0 :(得分:2)

这是愚蠢的,

NSDate().timeIntervalSinceDate(serverTime)    

不是

NSDate.timeIntervalSinceDate(serverTime)     

答案 1 :(得分:2)

您还应格式化日期,如下所示:

let dateString = "2015-09-15T00:01:44.8530546-06:00"
let dateFormatter = NSDateFormatter()
dateFormatter.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierISO8601)
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSSxxx"
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
if let serverTime = dateFormatter.dateFromString(dateString){
   serverTime  // "Sep 15, 2015, 3:01 AM"
}

enter image description here