Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current week number in Swift 3?

Tags:

swift3

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?

like image 304
DoubleSpace Avatar asked Nov 24 '16 09:11

DoubleSpace


People also ask

How do I get the current week number in Swift?

How to get the week number from a date. To get the ISO week number (1-53), use calendar. component(. weekOfYear, from: date ) .

How do you calculate current week number?

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.

How can I get tomorrow date in Swift?

Component, value: Int) -> Date { let noon = Calendar. current. date(bySettingHour: 12, minute: 0, second: 0, of: self)! return Calendar.


2 Answers

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.

like image 61
haider_kazal Avatar answered Oct 21 '22 08:10

haider_kazal


I think this is what you are looking for

NSCalendar.current.component(.weekOfYear, from: Date())
like image 32
gasho Avatar answered Oct 21 '22 07:10

gasho