快速从数组中获取开始日期和结束日期之间的日期

时间:2019-04-05 09:38:37

标签: ios swift3

由于我是新手,所以我停留了很长时间,试图从开始日期和结束日期之间的数组中获取日期。

我已经尝试过这些从[https://stackoverflow.com/questions/10216991/fetching-dates-which-comes-between-startdate-and-enddate], But I am getting the error as "Value of type '[Date]' has no member 'filtered'".引用的代码

迅速

var predicate = NSPredicate(format: "(SELF > %@) AND (SELF < %@)", startdate!, enddate!)
var result = arrayWithDates.filtered(using: predicate)

Expected output: 
dateArray = ["12/01/1996","13/01/1996","15/01/1996","17/01/1996"]
startdate = "13/01/1996" 
enddate = "17/01/1996"
output = ["13/01/1996","15/01/1996","17/01/1996"]

请先帮助我实现这一目标

3 个答案:

答案 0 :(得分:0)

您可以这样做:

import Foundation

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
dateFormatter.timeZone = TimeZone(abbreviation: "GMT")

let dateArray = ["12/01/1996","13/01/1996","15/01/1996","17/01/1996"]
let startdate = dateFormatter.date(from: "13/01/1996")!
let enddate = dateFormatter.date(from: "17/01/1996")!

let output = dateArray
    // Map your strings to Date objects excluding nils.
    .compactMap { dateFormatter.date(from: $0) }
    // Filter the mapped array by your condition.
    .filter { $0 >= startdate && $0 <= enddate }

答案 1 :(得分:0)

您可以尝试以下代码,它对我有用:

class ViewController: UIViewController {
var arrDates = NSArray()
var arrResultDates = NSMutableArray()
override func viewDidLoad() {
    super.viewDidLoad()

   arrDates = ["12/01/1996","13/01/1996","15/01/1996","17/01/1996"]
    let strStartDate = "\(arrDates.firstObject!)"
    let strEndDate = "\(arrDates.lastObject!)"
    let formatter  = DateFormatter()
    formatter.dateFormat = "dd/MM/yyyy"
    //Get start date
    var startDate = formatter.date(from: strStartDate)
    let endDate = formatter.date(from: strEndDate) // last date

    // Formatter for printing the date, adjust it according to your needs:
    let fmt = DateFormatter()
    fmt.dateFormat = "dd/MM/yyyy"
    let calendar = NSCalendar.current
    while startDate! <= endDate! {

        startDate = calendar.date(byAdding: .day, value: 1, to: startDate!)!
        let strDate = fmt.string(from: startDate!)
        if arrDates.contains(strDate)
        {
            arrResultDates.add(strDate)
        }
    }

    print(arrResultDates)

}

希望它将对您有帮助:)

答案 2 :(得分:0)

如果您确实需要使用NSPredicate,则必须将阵列桥接到NSArray,后者会响应filtered(using:

let predicate = NSPredicate(format: "(SELF > %@) AND (SELF < %@)", startdate!, enddate!)
let result = (arrayWithDates as NSArray).filtered(using: predicate)

但是,在Swift的世界中,不建议这样做。只需将filter函数与闭包一起使用

let result = arrayWithDates.filter { $0 >= startdate! && $0 <= enddate! }