ios - iOS 和 Swift 中 UTC 的登机时间和当前时间之间的差异

标签 ios swift dateformatter

我正在从服务中获取登机时间(比方说 BT-登机时间) 我需要找出 Boarding Time 和 current time 之间的差异,然后找出 Hour 和 Min 的差异。

条件是用户可以检查来自世界上任何国家的这些之间的差异。所以我使用 UTC 来计算,但它给出了正确的结果,请帮助我。

 func dayStringFromTime() -> String {
        let currentTimeUnix = Date().timeIntervalSince1970
        let date = NSDate(timeIntervalSince1970: currentTimeUnix)
        let dateFormatter = DateFormatter()
        //  dateFormatter.dateFormat = "HH:mm:ss"
        return date.description
    }

let CT  = dayStringFromTime() //time1
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-mm-dd HH:mm:ss"
let CTDate = formatter.date(from: CT)
let time1 = boardingDateTime//timeformatter.date(from: CT)
let time2 = CT_Date//timeformatter.date(from: ETD)
//You can directly use from here if you have two dates
let interval = time1.timeIntervalSince(time2! as Date)
let hour = (interval ) / 3600;
let minute = interval.truncatingRemainder(dividingBy: 3600) / 60
let intervalInt = Int(interval)
print("\(intervalInt < 0 ? "-" : "+") \(Int(hour)) Hours \(Int(Int(minute))) Minutes")
let minText = Int(minute) > 0 && Int(minute) != 0 ? " \(Int(minute)) min" : (Int(minute) < 0 ? " \(Int(abs(minute))) min" : "")
let hrText  = Int(hour) > 0 && Int(hour) != 0 ? " \(Int(hour)) hr" : (Int(hour) < 0 ? " \(Int(abs(hour))) hr" : "") 

此网址 https://stackoverflow.com/a/28608779/3400991显示有关此结果的确切问题,请帮助

最佳答案

这比你想象的要简单得多:

let boardingTime = Date().addingTimeInterval(3200) // the `addingTimeInterval` is for demonstration purposes only.
let now = Date()
let difference = Calendar.current.dateComponents([.hour, .minute, .second], from: now, to: boardingTime)
print("Boarding will be in: \(difference.hour!):\(difference.minute!):\(difference.second!)")

关于ios - iOS 和 Swift 中 UTC 的登机时间和当前时间之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53471839/

相关文章:

php - MYSQL 查询和 PHP - 向 IOS 应用程序返回 nil 的查询

ios - 如何自定义 xAxis 下的标签颜色?

ios - SpriteKit 场景中的对象定位

swift - 从 dateFormat 获取错误的日期

ios - Swift DateFormatter 返回错误的日期

ios - AppDelegate didFinishLaunchingWithOptions launchOptions 始终返回(null)

ios - 益智游戏中的某些 UIImageViews 不会移动到新的 CGPoint 中心

arrays - Swift:通过函数更改全局变量的值。

ios - 如何在 WebView 中添加 Pull to Refresh?

json - 如何在没有时区的情况下解析 ISO8061 日期