Search code examples
iosswiftnscalendar

NSCalendar week number of date


I am trying to get the week number from a date. Can someone please tell me why this is only returning 0 no matter what date I put in there:

let currentWeekNumber = NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitWeekOfYear, fromDate: myDate).weekOfYear

The format of myDate is like this 2015-01-23 11:52:35 +0000

A solution in Swift would be nice :)


Solution

  • Seems like your posted line has no error. Just check the below solution to confirm if result is same.

    Note: Just trying to eliminate any possiblity of irrelevant issue due to date. For Swift you can use.

    let calender = NSCalendar.currentCalendar()
    let dateComponent = calender.components(NSCalendarUnit.WeekOfYearCalendarUnit  | NSCalendarUnit.DayCalendarUnit  | NSCalendarUnit.MonthCalendarUnit  | NSCalendarUnit.YearCalendarUnit, fromDate:NSDate())
    
    println ("Week: = \(dateComponent.weekOfYear)")
    

    Hence response should be like below:

    Week: = 4