[英]Find difference in two dates in iOS
I am not sure what I am doing wrong, I need to find difference between two dates and extract seconds from it, below is my code. 我不确定自己在做什么错,我需要找出两个日期之间的差异并从中提取秒,这是我的代码。 I am not getting correct seconds.
我没有得到正确的秒数。 There is difference of seconds.
有几秒钟的差异。
public func captureStartTime() {
captureStartDateTime = Date()
}
public func captureEndTime(eventType: String, eventElement: String) {
let difference = Date().timeIntervalSince(captureStartDateTime)
let interval = Int(difference)
let seconds = interval % 60
let secondsDescrp = String(format: "%02d", seconds)
}
interval
is the answer you want. interval
是您想要的答案。 That is the total number of seconds between the two dates. 那是两个日期之间的总秒数。
Your seconds
value would only be useful if you wanted to calculate the number of hours, minutes, and seconds or the number of minutes and seconds from the total number of seconds. 仅当您要计算小时,分钟和秒数或从秒总数中计算出的分钟数和秒数时,
seconds
值才有用。
you can also use default date components and according to that compare your dates and you can get the difference in year, month, day etc 您还可以使用默认日期组成部分,并根据该日期进行比较,以获取年,月,日等之间的差额
let dateString1 = "2019-03-07T14:20:20.000Z"
let dateString2 = "2019-03-07T14:20:40.000Z"
//set date formate
let Dateformatter = DateFormatter()
Dateformatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
//convert string to date
let dateold = Dateformatter.date(from: dateString1)!
let datenew = Dateformatter.date(from: dateString2)!
//use default datecomponents with two dates
let calendar1 = Calendar.current
let components = calendar1.dateComponents([.year,.month,.day,.hour,.minute,.second], from: dateold, to: datenew)
let seconds = components.second
print("Seconds: \(seconds)")
Use the following code to get the difference between two dates, Store current time in startTime
when pressed button 1 and store current date time in endTime
when pressed button 2, See this code, I hope this helps you. 使用以下代码来获取两个日期之间的时差:按下按钮1时将当前时间存储在
startTime
,按下按钮2时将当前日期存储在endTime
,请参见以下代码,希望对您有所帮助。
var startTime:Date!
var endTime:Date!
@IBAction func buttonStartTime(_ sender: UIButton) {
startTime = Date()
}
@IBAction func buttonEndTime(_ sender: UIButton) {
endTime = Date()
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.second]
formatter.unitsStyle = .full
let difference = formatter.string(from: startTime, to: endTime)!
print(difference)//output "8 seconds"
}
Output 产量
8 seconds
8秒
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.