私は両方とも文字列形式で2回持っています:
timeOne = "12:58 AM"
timeTwo = "1:05 PM"
このようにNSDateに変換します
func convertTime(tim: String) -> NSDate{
let strDate = tim
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "HH:mm a"
//converts into NSDate so we can find the time remaining
return (dateFormatter.dateFromString(strDate))!
}
let tOne = convertTime(timeOne)
let tTwo = convertTime(timeTwo)
tOne と tTwo を変換すると、私が出力されます
tOne = 2000-01-01 00:58:00 +0000
tTwo = 2000-01-01 12:05:00 +0000
私は2回を比較しますが、7分を返したいのですが、「667」を取得しています 比較するコードは次のとおりです。
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.Minute, fromDate: tOne, toDate: tTwo, options: [])
print(components)
これは印刷されます
667
ただし、両方の時間が同じ AM または PM の場合は機能します。
tOne = "1:06 PM"
tTwo = "1:15 PM"
比較コードを実行すると、「9」が正常に出力されます