Get the first day of week without WeekCalendarUnit

前端 未结 1 1066
野的像风
野的像风 2021-01-14 05:38

I would like to get the first day of the week depending on a NSDate.

It works fine but I have a warning because WeekCalendarUnit is deprecated.

I made some

1条回答
  •  伪装坚强ぢ
    2021-01-14 06:19

    You can use .CalendarUnitWeekOfYear in combination with .CalendarUnitYearForWeekOfYear, this should give the intended result:

    let currentDateComponents = calendar.components(.CalendarUnitYearForWeekOfYear | .CalendarUnitWeekOfYear , fromDate: date)
    let startOfWeek = calendar.dateFromComponents(currentDateComponents)
    

    Alternatively, use rangeOfUnit() (which I personally find easier to use):

    var startOfWeek : NSDate?
    calendar.rangeOfUnit(.CalendarUnitWeekOfYear, startDate: &startOfWeek, interval: nil, forDate: date)
    

    In Swift 2 this has to be changed to

    let currentDateComponents = calendar.components([.YearForWeekOfYear, .WeekOfYear ], fromDate: date)
    let startOfWeek = calendar.dateFromComponents(currentDateComponents)
    

    and

    var startOfWeek : NSDate?
    calendar.rangeOfUnit(.WeekOfYear, startDate: &startOfWeek, interval: nil, forDate: date)
    

    0 讨论(0)
提交回复
热议问题