问题
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
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)
回答1:
Simply make extension of Date
like this and get difference in days.
extension Date {
func daysBetweenDate(toDate: Date) -> Int {
let components = Calendar.current.dateComponents([.day], from: self, to: toDate)
return components.day ?? 0
}
}
Now use this extension like this
let numOfDays = fromDate.daysBetweenDate(toDate: toDate)
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")
回答2:
Use this function to get all intermediate dates between two dates, just check if down date (final date) is greater than up date (first date) then order is +1, else order -1 :-
func selectDates(from upDate : Date, to downDate : Date, order : Int){
var selectDate = Calendar.current.date(byAdding: .day, value: order, to: upDate)!
while compareDate(dateInitial: selectDate, dateFinal: downDate) != true{
print(" intermediate date is \(selectDate)")
selectDate = Calendar.current.date(byAdding: .day, value: order, to: selectDate)!
}
print("*** intermediate dates are selected ***")
}
func compareDate(dateInitial:Date, dateFinal:Date) -> Bool {
let order = Calendar.current.compare(dateInitial, to: dateFinal, toGranularity: .day)
switch order {
case .orderedSame:
return true
default:
return false
}
}
回答3:
Try This One
let startDateComparisionResult:ComparisonResult = currentDate.compare(clickedDate! as NSDate)
if startDateComparisionResult == ComparisonResult.orderedAscending
{
// Current date is smaller than end date.
}
else if startDateComparisionResult == ComparisonResult.orderedDescending
{
// Current date is greater than end date.
}
else if startDateComparisionResult == ComparisonResult.orderedSame
{
// Current date and end date are same
}
回答4:
Try:
let days=Calendar.current.dateComponents([.day], from: date_1, to: date_2)
let nb_days=days.day
来源:https://stackoverflow.com/questions/40674599/how-can-i-compare-two-dates-nsdate-in-swift-3-and-get-the-days-between-them