如何有未来的5天在我的日期数组使用Swift NSDate通过取消每个星期日



我试图创建UIPickerView,让用户选择拍卖日期为5天。但是,根据我的要求,我需要禁用/隐藏/不添加与"星期日"有关的日子。我的意思是,如果今天是8/7/2015,我的UIPickerView中的数据将是

["All","08/07/2015 (Wed)","09/07/2015 (Thu)","10/07/2015 (Fri)", "11/07/2015 (Sat)","13/07/2015 (Mon)"]

如你所见,我把星期天藏在那个类别中。我试着找路,但仍然是错误的错误,请帮忙吗?

我的代码

import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
    var now = NSDate()
    var auctionDate = [String]()
    var sdfDDMMYYYYEEE = NSDateFormatter()
    sdfDDMMYYYYEEE.dateFormat = "dd/MM/yyyy (EEE)"
    var sdfDDMMYYYY = NSDateFormatter()
    sdfDDMMYYYY.dateFormat = "dd/MM/yyyy"
    var sdfEEE = NSDateFormatter()
    sdfEEE.dateFormat = "EEE"
    // This is how i
    var startTime : NSTimeInterval = (floor(now.timeIntervalSince1970)) + 86400000
    auctionDate.append("All")
    for var i = 0; i < 5; i++ {
        if sdfEEE.stringFromDate(now) == "Sun" {
            now = now.dateByAddingTimeInterval(startTime)
            i--;
            continue;
        }
        auctionDate.append(sdfDDMMYYYYEEE.stringFromDate(now) as String)
        now = now.dateByAddingTimeInterval(startTime)
    }
    println(auctionDate)
}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}

我在控制台得到那个输出

[All, 07/07/2015 (Tue), 07/01/2112 (Thu), 08/04/2160 (Tue), 09/07/2208 (Sat), 09/10/2256 (Thu)]

任何帮助。这个问题困扰我太久了

你的代码中有几个错误。

  • NSDate()NSTimeInterval()使用,而不是毫秒。86400000秒(大约)是1000天。
  • 即使增加86400秒也是错误的方法,因为一天可能在实行日光节约时间的地区有23或25小时。
  • 在"now = now.dateByAddingTimeInterval(startTime)"中添加号码
  • 将工作日名称与"Sun"进行比较在大多数情况下不起作用语言。

说了这么多,这里有一个可能的解决方案,使用适当的NSCalendar方法。有了嵌入的注释,它应该是不解自明的:

let cal = NSCalendar.currentCalendar()
let fmt = NSDateFormatter()
fmt.dateFormat = "dd/MM/yyyy (EEE)"
// Start with today (at midnight):
var date = cal.startOfDayForDate(NSDate())
var auctionDates = [ "All" ]
// Repeat until there are enough dates in the array:
while auctionDates.count < 6 {
    // Compute weekday of date (1 == Sunday)
    let weekDay = cal.component(.CalendarUnitWeekday, fromDate: date)
    // Add to array if not Sunday:
    if weekDay != 1 {
        auctionDates.append(fmt.stringFromDate(date))
    }
    // Advance one day:
    date = cal.dateByAddingUnit(.CalendarUnitDay, value: 1, toDate: date, options: nil)!
}
println(auctionDates)

最新更新