我想获得服务器UTC时间和本地时间之间的差异。 我在这里写了一些代码..
var localTime:String!
var timeString:String = "06:05:00" //This is server UTC time
let dateFormator = DateFormatter()
dateFormator.dateFormat = "H:mm:ss"
dateFormator.timeZone = TimeZone(abbreviation: "UTC")
let dt = dateFormator.date(from: timeString)
if dt != nil {
dateFormator.timeZone = TimeZone.current
dateFormator.dateFormat = "h:mm a"
localTime = dateFormator.string(from: dt!) //Converted current local time
}
let date = Date()
let dateFormatter2 = DateFormatter()
dateFormatter2.dateFormat = "h:mm a"
let timeStr = dateFormatter2.string(from: date)// Current time
let date1 = dt!
let date2 = dateFormatter2.date(from: timeStr)!
var _date1:String = localTime
var _date2:String = timeStr
//TODO: Remove the bellow two line and Comment *Line: 1 , Uncomment *Line: 2
//_date1 = "11:00"
//_date2 = "12:00"
let _dateFormatter = DateFormatter()
_dateFormatter.dateFormat = "HH:mm a" //*Line: 1
//_dateFormatter.dateFormat = "HH:mm" //*Line: 2
let date3 = _dateFormatter.date(from: _date1)
let date4 = _dateFormatter.date(from: _date2)
let _interval = date4!.timeIntervalSince(date3!)
let intervalInInt = Int(_interval)
let minutes3 = Int((_interval / 60).truncatingRemainder(dividingBy: 60))
let hours3 = Int((_interval / 3600))
String(format: "%02d:%02d", hours3, minutes3)
在此代码时间间隔中,当时间为HH:mm formate时,代码块工作正常,但我想检查“11:00 AM”之间的区别。 “下午1点”所以它失败了。所以请帮助我。提前谢谢。
答案 0 :(得分:1)
使用以下与本地时间戳
的区别let date = Date()
let timeZoneOffset = Double(TimeZone.current.secondsFromGMT(for: date))