我有两个Date
个对象,我想只比较它们之间的时差,忽略日期。
会是这样的:
dt1 =(日期)2016-09-22 20:05:01 UTC
dt2 =(日期)2016-08-20 22:06:00 UTC
并且dt1和dt2之间的差异将是2小时或121分钟。
Swift中有一个函数可以做到吗?
答案 0 :(得分:4)
您可以使用Calendar
提取DateComponents
,然后将日期,月份和年份与另一个的小时,分钟和秒组合成另一个Date
对象。然后,您可以使用记录良好的方法比较共享相同日期的两个Date
对象。
例如,给定date1
和date2
,我们可以计算date3
的日期date1
,但date2
的时间。然后,我们可以将date1
与此新date3
进行比较:
let calendar = Calendar.current
let components2 = calendar.dateComponents([.hour, .minute, .second], from: date2)
let date3 = calendar.date(bySettingHour: components2.hour!, minute: components2.minute!, second: components2.second!, of: date1)!
然后,获取date1
和date3
之间的分钟数:
let minutes = calendar.dateComponents([.minute], from: date1, to: date3).minute!
或小时和分钟:
let difference = calendar.dateComponents([.hour, .minute], from: date1, to: date3)
let hours = difference.hour!
let minutes = difference.minute!
或者,如果您想向用户展示这一点,您通常会使用DateComponentsFormatter
来获得一个不错的本地化字符串表示形式:
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .full
formatter.allowedUnits = [.hour, .minute] // or [.minute]
let string = formatter.string(from: date1, to: date3)!
答案 1 :(得分:1)
忽略日期,您可以使用timeIntervalSince(date:)获取两个日期之间的秒数。
答案 2 :(得分:0)
使用NSCalenar
,然后查找小时,分钟土地,然后找出它们之间的差异。
答案 3 :(得分:0)
Swift 3扩展用于比较仅限时间
import UIKit
extension Date {
func compareTimeOnly(to: Date) -> ComparisonResult {
let calendar = Calendar.current
let components2 = calendar.dateComponents([.hour, .minute, .second], from: to)
let date3 = calendar.date(bySettingHour: components2.hour!, minute: components2.minute!, second: components2.second!, of: self)!
let seconds = calendar.dateComponents([.second], from: self, to: date3).second!
if seconds == 0 {
return .orderedSame
} else if seconds > 0 {
// Ascending means before
return .orderedAscending
} else {
// Descending means after
return .orderedDescending
}
}
}
一些测试
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let date1 = Date()
var date2 = dateFormatter.date(from: "2016-12-26T12:12:12")!
let result = date1.compareTimeOnly(to: date2)
print(result.rawValue)
答案 4 :(得分:0)
func findsecond(s_date:String,e_date:String) -> Int {
//set date formate
let Dateformatter = DateFormatter()
Dateformatter.dateFormat = "dd MMM yyyy h:mm a"
//convert string to date
let dateold = Dateformatter.date(from: start_date)!
let datenew = Dateformatter.date(from: end_date)!
//use default datecomponents with two dates
let calendar1 = Calendar.current
let components = calendar1.dateComponents([.second], from: dateold, to: datenew)
let seconds = components.second
print("Seconds: \(seconds)")
return seconds!
}