Im trying to calculate the time difference between 18:00 & 06:00 and display the result in the same format. Both times are entered manually.
我试图计算18:00和06:00之间的时差,并以相同的格式显示结果。两次都是手动输入的。
1 个解决方案
#1
1
First create two NSDates from the string inputs and get the interval between the two then pass the interval through a formatting function we will create:
首先从字符串输入创建两个NSDate,然后获取两者之间的间隔,然后通过我们将创建的格式化函数传递间隔:
let date1:String = "12:00"
let date2:String = "13:00"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "HH:mm"
let date3 = dateFormatter.dateFromString(date1)
let date4 = dateFormatter.dateFromString(date2)
let interval = date4!.timeIntervalSinceDate(date3!)
print("\(stringFromTimeInterval(interval))")
now we need to format the interval which is the number of seconds between the two so create a function which returns a string:
现在我们需要格式化间隔,即两者之间的秒数,因此创建一个返回字符串的函数:
func stringFromTimeInterval(interval: NSTimeInterval) -> String {
let interval = Int(interval)
let minutes = (interval / 60) % 60
let hours = (interval / 3600)
return String(format: "%02d:%02d", hours, minutes)
}
in your case you will set the date1 and date2 from I'm guessing the text fields in your program.
在你的情况下,你将设置date1和date2,我猜你的程序中的文本字段。
#1
1
First create two NSDates from the string inputs and get the interval between the two then pass the interval through a formatting function we will create:
首先从字符串输入创建两个NSDate,然后获取两者之间的间隔,然后通过我们将创建的格式化函数传递间隔:
let date1:String = "12:00"
let date2:String = "13:00"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "HH:mm"
let date3 = dateFormatter.dateFromString(date1)
let date4 = dateFormatter.dateFromString(date2)
let interval = date4!.timeIntervalSinceDate(date3!)
print("\(stringFromTimeInterval(interval))")
now we need to format the interval which is the number of seconds between the two so create a function which returns a string:
现在我们需要格式化间隔,即两者之间的秒数,因此创建一个返回字符串的函数:
func stringFromTimeInterval(interval: NSTimeInterval) -> String {
let interval = Int(interval)
let minutes = (interval / 60) % 60
let hours = (interval / 3600)
return String(format: "%02d:%02d", hours, minutes)
}
in your case you will set the date1 and date2 from I'm guessing the text fields in your program.
在你的情况下,你将设置date1和date2,我猜你的程序中的文本字段。