swift 获取网络上的时间

1、

func getDate(_ sender: Any) {        
        let urlString = "http://m.baidu.com"
        
        
        let task = URLSession(configuration: URLSessionConfiguration.default).dataTask(with: URL(string: urlString)!) { (data, response, error) in
            
            
            if let httpresponse = response as? HTTPURLResponse {
                
                var dateString = httpresponse.allHeaderFields["Date"] as? String
                
                dateString = dateString?.substring(from: (dateString?.characters.index((dateString?.startIndex)!, offsetBy: 5))!)
                
                dateString = dateString?.substring(to: (dateString?.characters.index((dateString?.endIndex)!, offsetBy: -4))!)
                
                print(dateString)
                
                let datefmt = DateFormatter()
                datefmt.locale = Locale(identifier: "en_US")
                datefmt.dateFormat = "dd MMM yyyy HH:mm:ss"
                
                let date = datefmt.date(from: dateString!)?.addingTimeInterval(60*60*8)
                print(date)
                
                let zone = NSTimeZone.system
                
                let inter = zone.secondsFromGMT(for: date!)
                let locadate = date?.addingTimeInterval(TimeInterval(inter))
                print(locadate)

            }
            
        }
        task.resume()
        
    }
打印信息
Optional("14 Aug 2017 05:59:28")
Optional(2017-08-14 05:59:28 +0000)
Optional(2017-08-14 13:59:28 +0000)

你可能感兴趣的:(swift 获取网络上的时间)