如何在Swift 3中比较两个日期(NSDate)并计算它们之间的天数?

8

如何在Swift 3中比较两个日期? 我找到了许多适用于其他Swift版本的解决方案,但它们对我无效。

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 = ""
    }

我比较了这两个日期,但是我希望得到在这两个日期之间的天数。请问有人可以帮帮我吗? 谢谢! 补充说明: 如果我有一个日期为2016年11月22日和当前日期(现在是2016年11月18日),我想知道它们之间相差的天数(在这种情况下是4)。
4个回答

15

只需像这样扩展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 将字符串转换为日期,如下所示。

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
dateFormatter.timeZone = TimeZone(abbreviation: "GMT")
let date = dateFormatter.date(from: "18-11-2016")

我在哪里声明扩展名? - moxmlb
出现此错误:未解决的标识符'use of unresolved identifier 'fromDate'' - moxmlb
那个可行,但如果我有2016年11月18日(开始日期)和2016年11月22日(结束日期),它会显示3天。 - moxmlb
我如何为它们设置正确的时区?例如:dateAsString = clickedDay + "-11-2016 GMT" ?? - moxmlb
@Mbach请检查编辑后的答案,将字符串转换为日期,无需在您的日期字符串中添加“GMT”。 - Nirav D
显示剩余2条评论

3
尝试这个。
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
}

取决于你的 currentDate 和 clickedDate 的值。 - Sapana Ranipa

2

尝试:

let days=Calendar.current.dateComponents([.day], from: date_1, to: date_2)
let nb_days=days.day

我想知道还有多少天到达下一个日期。 - moxmlb
我不确定我理解你的意思。我的答案给出了从your_date到Date()(即今天)之间的天数。但是,如果您想与另一个日期进行比较,只需将Date()更改为next_date即可。 - Marie Dm
是的,那就是我想要的。但是我没有天数,我该如何获取天数? - moxmlb
抱歉,我忘记了第二部分 :) 我更新了我的回答@Mbach - Marie Dm

2
使用此函数获取两个日期之间的所有中间日期,只需检查down date(最终日期)是否大于up date(第一个日期),然后顺序为+1,否则顺序为-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
        }
    }

我想知道还有多少天到达下一个日期。 - moxmlb

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接