我希望在一周的第一天取决于NSDate. 它工作正常,但我有一个警告,因为不推荐使用WeekCalendarUnit. 我做了一些研究,我试图用以下代码替换WeekCalendarUnit: static var CalendarUnitWeekday: NSCalendarUn
它工作正常,但我有一个警告,因为不推荐使用WeekCalendarUnit.
我做了一些研究,我试图用以下代码替换WeekCalendarUnit:
static var CalendarUnitWeekday: NSCalendarUnit { get } static var CalendarUnitWeekdayOrdinal: NSCalendarUnit { get } static var CalendarUnitWeekOfMonth: NSCalendarUnit { get } static var CalendarUnitWeekOfYear: NSCalendarUnit { get }
但我没有相同的结果.这是我的垃圾代码:
var date = NSDate() dateFormatter.dateFormat = "dd/YY" let calendar = NSCalendar.currentCalendar() let currentDateComponents = calendar.components(.CalendarUnitYear | .WeekCalendarUnit , fromDate: date) let startOfWeek = calendar.dateFromComponents(currentDateComponents) var dteString = dateFormatter.stringFromDate(startOfWeek!) // Output is "17/15"
任何的想法?
您可以结合使用.CalendarUnitWeekOfYear.CalendarUnitYearForWeekOfYear,这应该给出预期的结果:
let currentDateComponents = calendar.components(.CalendarUnitYearForWeekOfYear | .CalendarUnitWeekOfYear , fromDate: date) let startOfWeek = calendar.dateFromComponents(currentDateComponents)
或者,使用rangeOfUnit()(我个人觉得更容易
使用):
var startOfWeek : NSDate? calendar.rangeOfUnit(.CalendarUnitWeekOfYear, startDate: &startOfWeek, interval: nil, forDate: date)
在Swift 2中,这必须改为
let currentDateComponents = calendar.components([.YearForWeekOfYear, .WeekOfYear ], fromDate: date) let startOfWeek = calendar.dateFromComponents(currentDateComponents)
和
var startOfWeek : NSDate? calendar.rangeOfUnit(.WeekOfYear, startDate: &startOfWeek, interval: nil, forDate: date)