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?
How to get the week number from a date. To get the ISO week number (1-53), use calendar. component(. weekOfYear, from: date ) .
According to our convention, each week starts with Sunday and ends on Saturday. So, suppose today is Monday and hence, the week number is also 1. After 20 days, the week number will be obviously 3rd. On carefully observing, we can see that week number after p days can be calculated using the formula mentioned below.
Component, value: Int) -> Date { let noon = Calendar. current. date(bySettingHour: 12, minute: 0, second: 0, of: self)! return Calendar.
Try the following code snippet. It is written in Swift 3.
let calendar = Calendar.current
let weekOfYear = calendar.component(.weekOfYear, from: Date.init(timeIntervalSinceNow: 0))
print(weekOfYear)
This will print the week of year.
I think this is what you are looking for
NSCalendar.current.component(.weekOfYear, from: Date())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With