iOS,Swift中UTC的登机时间与当前时间之间的时差

时间:2018-11-25 20:50:36

标签: ios swift dateformatter

我从服务中获得登机时间(比方说,BT-登机时间) 我需要找出登机时间与当前时间之间的差异,然后找出小时,分钟之间的差异。

条件是用户可以检查这些与世界上任何国家之间的差异。因此,我使用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显示了有关此结果的确切问题,请帮助

2 个答案:

答案 0 :(得分:2)

您可以轻松地做到这一点:

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!)")

答案 1 :(得分:1)

首先,对日期/时间数学要非常小心,它不是线性的线性转换,围绕着它的很多规则使它变得复杂。

您需要做的第一件事是计算两次之间的差,这对您来说很幸运,这相对容易...

var boardingTime = Date()
boardingTime = bordingTime.addingTimeInterval(Double.random(in: 0.0..<86400.0))
let now = Date()
let difference = boardingTime.timeIntervalSince(now)

这为您提供了这两个值之间的秒数(正值是到现在为止的时间,负值是到之后的时间)

接下来,您需要以某种人类可读的符号表示的小时/分钟。只是将所有内容乘以60似乎很诱人,但这将是一个错误,并导致您养成不良习惯(确保在短范围内还不错,但您需要非常小心)

更好的解决方案是使用DateComponentsFormatter ...

let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.hour, .minute]
formatter.unitsStyle = .abbreviated

formatter.string(from: difference)

这将为您处理所有“规则”,但是,它还将对结果进行本地化,始终是奖励。

上面的示例将打印类似...

10h 28m