23

I want to get the current week number and display it in my app. There are many examples online using the old WeekOfYearCalendarUnit, which would have solved my problem, but in true Apple fashion it's been deprecated and no alternative is offered. Iv'e managed to pull this function off that atleast display's the weeks of the year. But not the current one.

func weekYear(){

    let weekRange = NSCalendar.current.range(of: .weekOfYear, in: .yearForWeekOfYear, for: Date())

    print("\(weekRange?.count)")

}

My question is how to get the current week number with swift 3 in xcode 8.1?

DoubleSpace
  • 253
  • 1
  • 2
  • 4
  • 1
    Basically `yearForWeekOfYear` and `weekOfYear` are not deprecated, they have just been renamed from `YearForWeekOfYearCalendarUnit` and `WeekOfYearCalendarUnit` and turned into an enum. – vadian Nov 24 '16 at 10:05
  • 1
    `let numOFWeeks = Calendar.current.component(.weekOfYear, from: Date())` – Nirav D Nov 24 '16 at 10:06
  • 1
    Possible duplicate of [Get the Week Number in iOS SDK](http://stackoverflow.com/questions/17587697/get-the-week-number-in-ios-sdk) – haider_kazal Nov 24 '16 at 10:09

3 Answers3

41

Try the following code snippet. It is written in Swift 3.

let calendar = Calendar.current
let weekOfYear = calendar.component(.weekOfYear, from: Date(timeIntervalSinceNow: 0))
print(weekOfYear)

This will print the week of year.

haider_kazal
  • 3,448
  • 2
  • 20
  • 42
7

I think this is what you are looking for

NSCalendar.current.component(.weekOfYear, from: Date())
gasho
  • 1,926
  • 1
  • 16
  • 20
6

Try this

let calendar = NSCalendar.current
let component = calendar.component(.weekOfYear, from: Date())
Marius Fanu
  • 6,589
  • 1
  • 17
  • 19