如何在Swift 3中比较两个日期(NSDate)并获取它们之间的日期? [英] How can i compare two dates (NSDate) in Swift 3 and get the days between them?
本文介绍了如何在Swift 3中比较两个日期(NSDate)并获取它们之间的日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在Swift 3中比较两个日期?
我找到了许多其他Swift版本的解决方案,但它们对我不起作用。
How can I compare two dates in Swift 3? I found many solutions for other Swift versions, but they doesn't work for me.
let clickedDay:String = currentcell.DayLabel.text!
let currentDate = NSDate()
let currentDay = "" //want the current day
let dateFormatter = DateFormatter()
var dateAsString = ""
if Int(clickedDay)! < 10 {
dateAsString = "0" + clickedDay + "-11-2016 GMT"
}
else {
dateAsString = clickedDay + "-11-2016 GMT"
}
dateFormatter.dateFormat = "dd-MM-yyyy zzz"
let clickedDate = dateFormatter.date(from: dateAsString)
if currentDate as Date >= clickedDate! as Date {
return true
}
else {
//Want to get the days between the currentDate and clickedDate
let daysLeft = ""
}
我比较两个日期,但我希望两个日期之间的天数。
有人可以帮助我吗?
谢谢和问候
I compare the tow dates, but i want the days which are between that tow dates. Can someone help me pls? Thanks and greets
添加:
如果我有2016年11月22日和当前日期(现在为2016年11月18日),我希望(在这种情况下为4)
Added: If I have the date 22.11.2016 and the currentdate (now 18.11.2016) i want the days between that (in this case 4)
推荐答案
只需扩展 Date
extension Date {
func daysBetweenDate(toDate: Date) -> Int {
let components = Calendar.current.dateComponents([.day], from: self, to: toDate)
return components.day ?? 0
}
}
现在使用此扩展名
let numOfDays = fromDate.daysBetweenDate(toDate: toDate)
您可以使用 DateFormatter
这样将String转换为Date。
You can use DateFormatter
to convert String to Date like this.
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
dateFormatter.timeZone = TimeZone(abbreviation: "GMT")
let date = dateFormatter.date(from: "18-11-2016")
这篇关于如何在Swift 3中比较两个日期(NSDate)并获取它们之间的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文