我试图创建UIPickerView,让用户选择5天的拍卖日期。但是,根据我的要求,我需要禁用/隐藏/不添加与"星期日"相关的日子。我的意思是,如果今天是2015年8月7日,我的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)]
任何帮助,拜托。我长期坚持这个问题。
答案 0 :(得分:1)
您的代码中存在多个错误。
NSDate()
和NSTimeInterval()
使用秒,而不是毫秒。 86400000秒(大约)1000天。now = now.dateByAddingTimeInterval(startTime)
中,您可以添加号码
(毫秒)到当前日期根本没有意义。说了这么多,这是一个可能的解决方案,使用正确的
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)