我正在开发一个Swift应用程序。它有一个格式为dd-mm-yyyy
的字符串日期数组。同一日期可以多次出现。当我点击一个按钮时,我想获得所有数据,这些数据的月份等于当前日期的最后2个月。
例如:数组包含一些元素,如01-10-2013
,23-11-2013
,20-12-2013
,20-12-2013
,20-12-2013
和当前日期{{1} }。当我单击一个按钮时,包含月份20-12-2013
的所有数据都应保存在另一个数组中。
我该怎么做?
答案 0 :(得分:1)
使用NSCalendar
,NSDateFormatter
,NSDate
和NSDateComponents
:
import Foundation
let cal = NSCalendar.currentCalendar()
let formatter = NSDateFormatter()
formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
formatter.dateFormat = "dd-MM-yyyy"
let now = NSDate()
let target = cal.dateByAddingUnit(.CalendarUnitMonth, value: -2, toDate: now, options: nil)!
let targetcomps = cal.components(.CalendarUnitYear | .CalendarUnitMonth , fromDate: target)
let ary = ["01-10-2014", "23-11-2014", "20-12-2014", "20-12-2014", "20-10-2014"]
let result = ary.filter {
if let date = formatter.dateFromString($0) {
return targetcomps == cal.components(.CalendarUnitYear | .CalendarUnitMonth , fromDate: date)
}
return false
}
println(result)
答案 1 :(得分:0)
尝试以下swift数组过滤器,
let array = ["01-10-2013", "23-11-2013", "20-12-2013", "20-12-2013", "20-12-2013"];
var iIndex = 0
let filteredArray = array.filter {
let myDate = $0 as NSString
let currentMonth = 12 // get it dynamically
let currentDate = 20 // get it dynamically
let currentYear = 2014
let monthToCompare = currentMonth - 2
if(
myDate.substringWithRange(NSRange(location: 0, length: 2)) == ("" + currentDate)
&& myDate.substringWithRange(NSRange(location: 3, length: 2)) == ("" + monthToCompare)
&& myDate..substringWithRange(NSRange(location: 6, length: 4)) == ("" + currentYear)
){
println("Original Index"+\(iIndex))
return true
}else{
return false
}
iIndex++
}
println(filteredArray) // This should have filtered array