Search code examples
swiftdateweek-number

Swift - Print what the current week of the year is


I need a way of printing the number of weeks so far this year.
I have managed to print the number of days and also the number of months (see the code below).
But cannot figure out how to do the same for the total number of weeks.

Total days so far this year:

let dateDay = Date()
                        let dateFormatterDay = DateFormatter()
                        dateFormatterDay.dateFormat = "DD"
                        let dateByDay = dateFormatterDay.string(from: dateDay)
                        print(dateByDay)

Total months so far this year:

 let dateMonth = Date()
                        let dateFormatterMonth = DateFormatter()
                        dateFormatterMonth.dateFormat = "MM"
                        let dateByMonth = dateFormatterMonth.string(from: dateMonth)
                        print(dateByMonth)

Solution

  • Try the following code snippet. It is written in Swift 4 and Swift 5.

    let currentDate = Date() 
    print(currentDate.dayOfYear)   // Day of Year
    print(currentDate.weekOfYear)  // Week of Year
    print(currentDate.monthOfYear) // Month of Year
    

    This will print the total days, weeks & months of the year respectively.

    extension Date {
        public var dayOfYear: Int {
            return Calendar.current.ordinality(of: .day, in: .year, for: self)!
        }
        public var weekOfYear: Int {
            return Calendar.current.ordinality(of: .weekOfYear, in: .year, for: self)!
        }
        public var monthOfYear: Int {
            return Calendar.current.ordinality(of: .month, in: .year, for: self)!
        }
    }