获取没有WeekCalendarUnit的一周的第一天

时间:2015-05-19 15:57:34

标签: swift nsdate

我希望在一周的第一天取决于NSDate。

它工作正常,但我有一个警告,因为不推荐使用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" 

任何想法?

1 个答案:

答案 0 :(得分:11)

您可以结合使用.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)